简体   繁体   English

如何在Swift中旋转UIButton?

[英]How do I rotate an UIButton in Swift?

I used to rotate an image this way: 我以这种方式旋转图像:

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

But this code doesn't work for a button: 但是这个代码对按钮不起作用:

let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI)

But I don't know how to assign that rotation to the button. 但我不知道如何将旋转分配给按钮。 How can I do it? 我该怎么做?

You have created a CABasicAnimation . 您已经创建了CABasicAnimation You should now add it to a CALayer . 您现在应该将它添加到CALayer Try using this code: 尝试使用此代码:

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

Set a duration this way: 以这种方式设置持续时间:

let duration = 1.0
rotateAnimation.duration = duration

A UIButton has a layer Property. UIButton有一个图层属性。

Just add your animation to the layer of your button. 只需将动画添加到按钮图层即可。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM