ios - 旋转 NSView 360 度

标签 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 重新创建它,但使用上面的代码似乎不起作用。 谢谢

最佳答案

它可以工作,但你必须改变两件事:

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/

相关文章:

ios - "Reinitialize"共享实例

ios - iOS 中的正则表达式将文本字段限制为仅字母和单个撇号

clang 以错误的方式优化了代码

xcode - 为 Photoshop CS5 构建插件需要哪些工具?

ios - 保持一些单元格高度不变,同时改变其他的

ios - 如何删除 UIStackView 中两个 tableview 之间的空间?

ios - XCode 5,分析器警告

macos - NSTableView 可编辑标题并双击表格单元格

ios - 如何实现 URLSessionDelegate 以允许自签名证书? (iOS/swift )

objective-c - 将 obj-c 库导入到 swift 会导致解析问题