Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate Text Change of UILabel

Tags:

I want to animate text changes in a UILabel.

For example: old text moves up and new text moves in from the bottom.

I already realised that I would need to labels. One for the old and one for the new text. The second UILabel is located below the first. Then both animate up.

However, how do you cut off the first label as it animates past the top portion of the frame?

like image 539
Joey Green Avatar asked Nov 10 '15 14:11

Joey Green


1 Answers

Use aUIView Extension

Animate in place using a single label:
- Leverage upon the built-in CALayer animations, and a UIView extension
- In the Storyboard, place the UILabel inside a UIView with Clip Subviews flag.
- pushTransition is applicable to most UIView

1. Extension

// Usage: insert view.pushTransition right before changing content extension UIView {     func pushTransition(_ duration:CFTimeInterval) {         let animation:CATransition = CATransition()         animation.timingFunction = CAMediaTimingFunction(name:             kCAMediaTimingFunctionEaseInEaseOut)         animation.type = kCATransitionPush         animation.subtype = kCATransitionFromTop         animation.duration = duration         layer.add(animation, forKey: kCATransitionPush)     } } 

2. Invocation

if let aLabel = label {     aLabel.pushTransition(0.4) // Invoke before changing content     aLabel.text = "\(count)"     count += 1 } 

3. Example

Animation with a kCAMediaTimingFunctionEaseInEaseOut curve, a 0.4 second duration, and a kCATransitionFromTop direction .

CALayer Animation


(†) Clipping is an important step for desired effect.

Swift 2 and earlier, see Steve Baughman's comment:
self.layer.addAnimation(animation, forKey: kCATransitionPush)

► Find this solution on GitHub and additional details on Swift Recipes.

like image 66
SwiftArchitect Avatar answered Sep 18 '22 05:09

SwiftArchitect