Skip to content

Instantly share code, notes, and snippets.

@boherna
Last active November 1, 2023 23:57
Show Gist options
  • Save boherna/9e3d223be4c8f2491a87 to your computer and use it in GitHub Desktop.
Save boherna/9e3d223be4c8f2491a87 to your computer and use it in GitHub Desktop.
To animate (fade) text change in UILabel (SWIFT)
The proper way to fade a UILabel (or any UIView for that matter) is to use a Core Animation Transition. This will not flicker, nor will it fade to black if the content is unchanged.
A portable and clean solution is to use a Extension in Swift (invoke prior changing visible elements)
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(duration:CFTimeInterval) {
let animation:CATransition = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionFade
animation.duration = duration
self.layer.addAnimation(animation, forKey: kCATransitionFade)
}
}
Invocation looks like this:
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = xxx
@kwolk
Copy link

kwolk commented Nov 1, 2023

Hola.

I tidied this up for XCode 10 (yea, I know) specifically for UILabel use, but it's still not working for me:

extension UILabel {
    func fadeTransition(duration: CFTimeInterval) {
        let animation: CATransition = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        animation.type = CATransitionType.fade
        animation.duration = duration
        self.layer.add(animation, forKey: CATransitionType.fade.rawValue)
    }

@kwolk
Copy link

kwolk commented Nov 1, 2023

This however did work:

UILabel.animate(withDuration: 0.5,
                delay       : 1.0,
                options     : [.repeat, .autoreverse, .curveEaseOut],
                animations  : { textLabel.alpha = 0.0 }) { (finished) in textLabel.alpha = 1.0 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment