我在下面有这段代码可以将 UIView 旋转 360 度。 是UIView的扩展文件。
extension NSView {
func rotate360Degrees(duration: CFTimeInterval = 0.5, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2.0)
rotateAnimation.duration = duration
if let delegate: AnyObject = completionDelegate {
rotateAnimation.delegate = delegate
}
self.layer.addAnimation(rotateAnimation, forKey: nil)
}
}
单击按钮后,我将使用 refreshButton.rotate360Degrees()
启动动画。
我想为 NSView 重新创建它,但使用上面的代码似乎不起作用。 谢谢
最佳答案
它可以工作,但你必须改变两件事:
extension NSView {
func rotate360Degrees(duration: CFTimeInterval = 0.5, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(M_PI * 2.0)
rotateAnimation.duration = duration
if let delegate: AnyObject = completionDelegate {
rotateAnimation.delegate = delegate
}
// `addAnimation` will execute *only* if the layer exists
self.layer?.addAnimation(rotateAnimation, forKey: nil)
}
}
- 在
self.layer
之后添加?
以允许在层不可用时有条件地执行。
如果您愿意,可以使用if let ...
:
if let theLayer = self.layer {
theLayer.addAnimation(rotateAnimation, forKey: nil)
}
- 将 View 的
wantsLayer
设置为true
,以强制 View 支持图层( View 在 OS X 上不会自动支持图层)。
关于ios - 旋转 NSView 360 度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30280947/