旋转NSView 360度

时间:2015-05-16 21:26:47

标签: ios macos swift animation nsview

我有以下代码来旋转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重新创建它,但它似乎没有使用上面的代码。 感谢

1 个答案:

答案 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)
    } 
  • 为您的视图设置wantsLayertrue,以强制视图为图层备份(视图不会在OS X上自动进行图层备份)。