Search code examples
swiftcocoansanimationcontext

Change NSTextField text color with fade animation - Cocoa


I am trying to change NSTextField text color with fade animation by using NSAnimationContext. 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
        }
   }

Solution

  • Here is the outline of one possible solution:

    • Subclass NSAnimation, say with TextColorAnimation
    • Have the init take the NSTextField and final NSColor
    • Override currentProgress as per NSAnimation docs to (a) call the super implementation and (b) set the intermediate color and display the NSTextField
    • Use NSColor.blend(...) to determine the intermediate color
    • start this NSAnimation

    You should get a nice smooth color transition. HTH