使用Swift动画循环进度

时间:2014-07-22 16:49:04

标签: ios swift cabasicanimation

当用户点击此自定义控件时,我尝试使用UIBezierPath为弧设置动画。 bezier路径只是向前捕捉而没有任何动画。

我覆盖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
    }
}

1 个答案:

答案 0 :(得分:0)

你无法在IB内部制作动画。您可以在游乐场中执行此操作,但IB仅用于布局 - 它不执行动画。您必须在模拟器或游乐场中预览。