简体   繁体   English

使用淡入淡出动画更改 NSTextField 文本颜色 - Cocoa

[英]Change NSTextField text color with fade animation - Cocoa

I am trying to change NSTextField text color with fade animation by using NSAnimationContext .我正在尝试使用NSAnimationContext更改带有淡入淡出动画的NSTextField文本颜色。 But it's not working.但它不起作用。 Please help me to solve this issue.请帮我解决这个问题。 Thanking you all!谢谢大家!

Code:代码:

 override func viewDidLoad() {
        super.viewDidLoad()
 
        label!.animator().textColor = NSColor.black
    }
    
    @IBAction func changeColor(_ sender: NSButton){
        
        NSAnimationContext.runAnimationGroup { (context) in
            
            context.duration = 1.0
            label!.animator().textColor = NSColor.red
        }
   }

Here is the outline of one possible solution:以下是一种可能的解决方案的概要:

  • Subclass NSAnimation , say with TextColorAnimation子类NSAnimation ,比如TextColorAnimation
  • Have the init take the NSTextField and final NSColorinit获取NSTextField和最终NSColor
  • Override currentProgress as per NSAnimation docs to (a) call the super implementation and (b) set the intermediate color and display the NSTextField根据NSAnimation文档覆盖currentProgress以 (a) 调用超级实现和 (b) 设置中间颜色并display NSTextField
  • Use NSColor.blend(...) to determine the intermediate color使用NSColor.blend(...)确定中间色
  • start this NSAnimation start这个NSAnimation

You should get a nice smooth color transition.你应该得到一个很好的平滑的颜色过渡。 HTH HTH

Update the color and alpha value in the completion handler:更新完成处理程序中的颜色和 alpha 值:

@IBAction func changeColor(_ sender: NSButton){
    NSAnimationContext.runAnimationGroup({ [self] context in
        context.duration = 1.0
        context.timingFunction = CAMediaTimingFunction(name: .easeOut)
        label.animator().alphaValue = 0.0
        label.animator().textColor = NSColor.black
    }, completionHandler: { [self] in
        NSAnimationContext.runAnimationGroup({ [self] context in
            context.duration = 1.0
            context.timingFunction = CAMediaTimingFunction(name: .easeIn)
            label.animator().alphaValue = 1.0
            label.animator().textColor = NSColor.red
        }, completionHandler: {
        })
    })
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM