如何在 Swift 中旋转 UIButton?

How do I rotate an UIButton in Swift?

我曾经这样旋转图像:

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)

但我不知道如何将旋转分配给按钮。我该怎么做?

只需将动画添加到按钮层即可。

//If you want a duration
rotateAnimation.duration = yourDuration

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

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

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

以这种方式设置持续时间:

let duration = 1.0
rotateAnimation.duration = duration

A UIButton 有层 属性.