UILabel的动画文本更改 [英] Animate Text Change of UILabel
问题描述
我想为UILabel中的文本更改设置动画.
例如:旧文本向上移动,新文本从底部移动.
For example: old text moves up and new text moves in from the bottom.
我已经意识到我需要贴标签.一个用于旧文本,一个用于新文本.第二个UILabel
位于第一个UILabel
之下.然后两者都进行动画处理.
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?
推荐答案
使用UIView
扩展名
Use aUIView
Extension
使用单个标签对就地动画 :
-利用内置的CALayer
动画和UIView
扩展名
-在情节提要中,将UILabel
放在具有 Clip Subviews 标志†的UIView
内.
-pushTransition
适用于大多数UIView
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.扩展程序
// 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.调用
if let aLabel = label {
aLabel.pushTransition(0.4) // Invoke before changing content
aLabel.text = "\(count)"
count += 1
}
3.示例
具有kCAMediaTimingFunctionEaseInEaseOut
曲线,0.4
秒持续时间和kCATransitionFromTop
方向†的动画.
Animation with a kCAMediaTimingFunctionEaseInEaseOut
curve, a 0.4
second duration, and a kCATransitionFromTop
direction †.
(†)裁剪是获得理想效果的重要步骤.
(†) Clipping is an important step for desired effect.
Swift 2和更早版本,请参见 Steve Baughman 的评论:
self.layer.addAnimation(animation, forKey: kCATransitionPush)
Swift 2 and earlier, see Steve Baughman's comment:
self.layer.addAnimation(animation, forKey: kCATransitionPush)
►在 GitHub 上找到此解决方案,并在
► Find this solution on GitHub and additional details on Swift Recipes.
这篇关于UILabel的动画文本更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!