【问题标题】:Sliding Animation NSView background color in swift快速滑动动画NSView背景颜色
【发布时间】:2018-03-04 05:40:36
【问题描述】:

尝试用像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

【问题讨论】:

  • 没有修改背景颜色,而是改变视图
  • @yerpy 视图如何改变?背景颜色仍然改变,但没有持续时间。
  • 视图从一侧移动并与后面的视图重叠,可能您可以使用集合视图并且每个单元格将有 2 个视图,即使您可以有一个堆栈视图,一个视图也会有宽度 = 0 和第二个视图宽度 = 堆栈视图宽度。但是你仍然会有左 - 右过渡。这似乎是轮播效应。
  • 哦!你在谈论谷歌趋势页面。在短时间内添加subview 是一项开销。因为您不想堆叠许多子视图(或者必须处理删除前一个子视图)。这就是我选择背景动画的原因。

标签: swift macos animation nsview


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2012-12-18
    • 2023-03-11
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多