ios - 使用 Swift 动画循环进度

标签 ios swift cabasicanimation

当用户单击此自定义控件时,我正在尝试使用 UIBezierPath 为圆弧设置动画。贝塞尔曲线路径简单地向前捕捉,没有任何动画。

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

最佳答案

您不能在 IB 内部制作动画。您也许可以在 Playground 上执行此操作,但 IB 仅用于布局 - 它不执行动画。您必须在模拟器或 playgrounds 中预览。

关于ios - 使用 Swift 动画循环进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24893216/

相关文章:

ios - 如何在 Swift 3 中设置状态栏样式

swift - 在 Swift 中,我可以在元组中使用函数类型吗?

ios - 以编程方式添加的 UIView 的动画将宽度分成两半

ios - 在 UITextView 上点击时不调用 UICollectionView didSelectItemAtIndexPath

ios - 更新自动布局约束以重新定位文本字段

ios - 不同导航 View Controller 上的后退按钮不同

ios - 在安装的 phonegap 中使用拖放

swift - 使用 Swift iOS13 在 UITextView 中自定义嵌入式超链接

ios - 我怎样才能使线路转弯?

ios - CABasicAnimation 有时有效,有时失败