我有一个按钮,当点击它时,它应该自行旋转,这是我的代码:
@IBAction func calculateButtonTapped(_ sender: UIButton) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI)
rotateAnimation.speed = 3.0
rotateAnimation.repeatCount = 6000
calculateButton.layer.add(rotateAnimation, forKey: nil)
DispatchQueue.main.async {
self.openCircle(withCenter: sender.center, dataSource: self.calculator!.iterateWPItems())
self.calculateButton.layer.removeAllAnimations()
}
}
但是,有时当我点击按钮时,它会立即返回正常状态然后旋转,有时按钮会变为暗选择状态,并且根本不动画,动画之后的任务将完成。如果我不停止动画,它会在 openCircle
完成后开始。
可能是什么原因?
最佳答案
- 您没有设置动画的
持续时间
。 替换这个
rotateAnimation.speed = 3.0
有了这个
rotateAnimation.duration = 3.0
-
@alexburtnik and it's ok to block the main thread
不,这不行。您应该在 openCircle
方法中添加一个 completion
参数,并在动画(或其他内容)完成时调用它。如果阻塞主线程,用户界面将会卡住,强烈建议不要这样做。
- 如果您不确定在主线程上调用了
calculateButtonTapped
,您也应该分派(dispatch)方法的第一部分。与 UI 相关的所有内容必须在主线程上完成。
它看起来应该类似于:
@IBAction func calculateButtonTapped(_ sender: UIButton) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI)
rotateAnimation.duration = 3.0
rotateAnimation.repeatCount = .infinity //endless animation
calculateButton.layer.add(rotateAnimation, forKey: nil)
self.openCircle(
withCenter: sender.center,
dataSource: self.calculator!.iterateWPItems(),
completion: {
self.calculateButton.layer.removeAllAnimations()
})
}
func openCircle(withCenter: CGPoint, dataSource: DataSourceProtocol, completion: (()->Void)?) {
//do your staff and call completion when you're finished
//don't block main thread!
}
关于ios - 旋转按钮动画不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40376737/