2014-07-22 59 views
3

我试图在用户单击此自定义控件时使用UIBezierPath动画圆弧。贝塞尔路径只是简单地向前捕捉而没有任何动画。使用Swift动画圆形进度

我重写drawrect的原因是因为我想在界面构建器中显示此自定义控件。在界面构建器中显示循环进度并让进度变为动画有什么好方法吗?

这里是我的代码:

import Foundation 
import UIKit 
import QuartzCore 

@IBDesignable class CircleControl:UIControl { 
    @IBInspectable var progressTotal:CGFloat = 100 

    @IBInspectable var progressCounter:CGFloat = 20 
    { 
    willSet(newProgressCounter) { 
     let animation = CABasicAnimation(keyPath: "strokeEnd") 
     animation.duration = 0.5; 
     animation.toValue = newProgressCounter; 
     animation.delegate = self; 
     layer.addAnimation(animation, forKey: "strokeEnd") 
    } 

    didSet { 
     setNeedsDisplay() 
    } 
    } 

    override func drawRect(rect: CGRect) { 
     let center = CGPointMake(bounds.size.width/2, bounds.size.height/2) 
     let radius = bounds.size.width/2; 
     let pi = CGFloat(M_PI) 
     let sliceAngle:CGFloat = (2 * pi)/progressTotal 

     let progressAngle:CGFloat = sliceAngle * progressCounter 
     let startAngle:CGFloat = CGFloat(-M_PI_2) + sliceAngle 
     let endAngle:CGFloat = startAngle + progressAngle; 

     let path = UIBezierPath() 
     path.addArcWithCenter(center, radius: radius - 5, startAngle: startAngle, endAngle: endAngle, clockwise: true) 
     path.lineWidth = 5 
     path.stroke() 
    } 

    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { 
     println("touch") 

     self.progressCounter = 80 
    } 

    override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { 
     self.progressCounter = 20 
    } 
} 
+0

您正试图在IB内动画? – Jeef

回答

0

不能IB内部动画。你可能可以在操场上做到这一点,但IB仅用于布局 - 它不会做动画。您必须在模拟器或游乐场预览。