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
}
}
CodePudding user response:
Here is the outline of one possible solution:
- Subclass
NSAnimation
, say withTextColorAnimation
- Have the
init
take theNSTextField
and finalNSColor
- Override
currentProgress
as perNSAnimation
docs to (a) call the super implementation and (b) set the intermediate color anddisplay
theNSTextField
- Use
NSColor.blend(...)
to determine the intermediate color start
thisNSAnimation
You should get a nice smooth color transition. HTH
CodePudding user response:
Update the color and alpha value in the completion handler:
@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: {
})
})
}