在swift中滑动动画NSView背景颜色

时间:2018-03-04 05:40:36

标签: swift macos animation nsview

尝试使用Google Trends

等滑动动画修改NSView的颜色
let hexColors = ["56A55B", "4F86EC", "F2BC42", "DA5040"]

@IBAction func changeColor(sender: NSButton) {
    let randomIndex = Int(arc4random_uniform(UInt32(hexColors.count)))
    NSAnimationContext.runAnimationGroup({_ in
        //duration
        NSAnimationContext.current.duration = 5.0
        self.view.animator().layer?.backgroundColor = NSColor(hex: hexColors[randomIndex]).cgColor
    }, completionHandler:{
        print("completed")
    })
}

我尝试使用NSAnimationContext来设置颜色更改的持续时间,但它不起作用。但是它适用于视图的alphaValue

1 个答案:

答案 0 :(得分:0)

我不确定您是否已经得到答案。但这也许可以让它发挥作用:

let hexColors = ["56A55B", "4F86EC", "F2BC42", "DA5040"]

@IBAction func changeColor(sender: NSButton) {
let randomIndex = Int(arc4random_uniform(UInt32(hexColors.count)))
NSAnimationContext.runAnimationGroup({ context in
    //duration
    context.duration = 5.0
    
    // This is the key property that needs to be set
    context.allowsImplicitAnimation = true

    self.view.animator().layer?.backgroundColor = NSColor(hex: hexColors[randomIndex]).cgColor
}, completionHandler:{
    print("completed")
})
}

文档内容如下:

/* Determine if animations are enabled or not. Using the -animator proxy will automatically set allowsImplicitAnimation to YES. When YES, other properties can implicitly animate along with the initially changed property. For instance, calling [[view animator] setFrame:frame] will allow subviews to also animate their frame positions. This is only applicable when layer backed on Mac OS 10.8 and later. The default value is NO.
 */
@available(macOS 10.8, *)
open var allowsImplicitAnimation: Bool