ios – 使用animateKeyframesWithDuration在屏幕上创建一个连续旋转的方块

我尝试使用下面的代码在屏幕上创建一个连续旋转的方块.但我不知道为什么转速在变化.如何更改代码以使旋转速度不变?我尝试了不同的UIViewKeyframeAnimationoptions,但似乎没有一个工作.
override func viewDidLoad() {
    super.viewDidLoad()

    let square = UIView()
    square.frame = CGRect(x: 55,y: 300,width: 40,height: 40)
    square.backgroundColor = UIColor.redColor()
    self.view.addSubview(square)

    let duration = 1.0
    let delay = 0.0
    let options = UIViewKeyframeAnimationoptions.Repeat
        UIView.animateKeyframesWithDuration(duration,delay: delay,options: options,animations: {
        let fullRotation = CGFloat(M_PI * 2)

        UIView.addKeyframeWithRelativeStartTime(0,relativeDuration: 1/3,animations: {
            square.transform = CGAffineTransformMakeRotation(1/3 * fullRotation)
        })                        
        UIView.addKeyframeWithRelativeStartTime(1/3,animations: {
            square.transform = CGAffineTransformMakeRotation(2/3 * fullRotation)
        })                        
        UIView.addKeyframeWithRelativeStartTime(2/3,animations: {
            square.transform = CGAffineTransformMakeRotation(3/3 * fullRotation)
        })
        },completion: {finished in
        })
    }

解决方法

这真的很奇怪… UIView.animateKeyframesWithDuration不能正常工作,因为我希望它与UIViewKeyframeAnimationoptions.CalculationModeLinear | UIViewKeyframeAnimationopti ons.Repeat传入了选项.

如果使用非块方法创建关键帧动画(请参见下文),则旋转将按预期重复.

如果我发现为什么基于块的选项不起作用,我会尝试记住在这里更新答案!

override func viewDidLoad() {
    super.viewDidLoad()


    let square = UIView()
    square.frame = CGRect(x: 55,height: 40)
    square.backgroundColor = UIColor.redColor()
    self.view.addSubview(square)

    let fullRotation = CGFloat(M_PI * 2)

    let animation = CAKeyframeAnimation()
    animation.keyPath = "transform.rotation.z"
    animation.duration = 2
    animation.removedOnCompletion = false
    animation.fillMode = kCAFillModeForwards
    animation.repeatCount = Float.infinity
    animation.values = [fullRotation/4,fullRotation/2,fullRotation*3/4,fullRotation]

    square.layer.addAnimation(animation,forKey: "rotate")

}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...