我尝试使用下面的代码在屏幕上创建一个连续旋转的方块.但我不知道为什么转速在变化.如何更改代码以使旋转速度不变?我尝试了不同的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")
- }