如何在 Swift 中旋转 UIButton?

3

我以前是这样旋转图片的:

self.image.transform = CGAffineTransformRotate(self.image.transform, 
                                      CGFloat(M_PI))

但是这段代码对于按钮无效:
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI)

但我不知道如何将该旋转赋给按钮,我该怎么做?

2个回答

4

您已经创建了一个CABasicAnimation。现在应该将其添加到CALayer中。 请尝试使用以下代码:

button.layer.addAnimation(rotateAnimation, forKey: "myAnimationKey");

可以通过以下方式设置持续时间:

let duration = 1.0
rotateAnimation.duration = duration

UIButton有一个layer属性。


我感谢您的解释。谢谢! - Cesare

1
只需将动画添加到按钮的图层即可。
//If you want a duration
rotateAnimation.duration = yourDuration

//You can set a key, but must not.
button.layer.addAnimation(rotateAnimation, forKey: nil)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接