I have this code below to rotate a UIView 360 degrees. It is an extension file of 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)
}
}
When the button is clicked I then use refreshButton.rotate360Degrees()
to start the animation.
I would like to recreate this for NSView but It does not seem to be working using the code above. Thanks
It works but you have to change two things:
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)
}
}
?
after self.layer
to allow conditional execution if the layer isn't available. You could use if let ...
if you prefer:
if let theLayer = self.layer {
theLayer.addAnimation(rotateAnimation, forKey: nil)
}
wantsLayer
to true
for your view, to force the view to be layer-backed (views are not automatically layer-backed on OS X).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.