我有以下代码来旋转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重新创建它,但它似乎没有使用上面的代码。 感谢
答案 0 :(得分:2)
它有效,但你必须改变两件事:
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)
}
wantsLayer
为true
,以强制视图为图层备份(视图不会在OS X上自动进行图层备份)。