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?
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 †.
(†) 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With