ios UILabel 中的动画文本更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3073520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Animate text change in UILabel
提问by Joo Park
I'm setting a new text value to a UILabel
. Currently, the new text appears just fine. However, I'd like to add some animation when the new text appears. I'm wondering what I can do to animate the appearance of the new text.
我正在将一个新的文本值设置为UILabel
. 目前,新文本显示得很好。不过,我想新的文本出现时添加一些动画。我想知道我可以做些什么来动画新文本的外观。
采纳答案by Joo Park
Here is the code to make this work.
这是使这项工作的代码。
[UIView beginAnimations:@"animateText" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:1.0f];
[self.lbl setAlpha:0];
[self.lbl setText:@"New Text";
[self.lbl setAlpha:1];
[UIView commitAnimations];
回答by Anton Gaenko
I wonder if it works, and it works perfectly!
我想知道它是否有效,而且效果很好!
Objective-C
目标-C
[UIView transitionWithView:self.label
duration:0.25f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.label.text = rand() % 2 ? @"Nice nice!" : @"Well done!";
} completion:nil];
Swift 3, 4, 5
斯威夫特 3、4、5
UIView.transition(with: label,
duration: 0.25,
options: .transitionCrossDissolve,
animations: { [weak self] in
self?.label.text = (arc4random()() % 2 == 0) ? "One" : "Two"
}, completion: nil)
回答by SwiftArchitect
Objective-C
目标-C
To achieve a truecross-dissolve transition (old label fading out whilenew label fading in), you don't want fade to invisible. It would result in unwanted flicker even if text is unchanged.
为了实现真正的交叉溶解过渡(旧标签淡出而新标签淡入),您不希望淡入淡出。即使文本未更改,也会导致不必要的闪烁。
Use this approach instead:
改用这种方法:
CATransition *animation = [CATransition animation];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = kCATransitionFade;
animation.duration = 0.75;
[aLabel.layer addAnimation:animation forKey:@"kCATransitionFade"];
// This will fade:
aLabel.text = "New"
Also see: Animate UILabel text between two numbers?
另请参阅: 在两个数字之间动画 UILabel 文本?
Demonstration in iOS 10, 9, 8:
示范在IOS 10,9%,8:
Tested with Xcode 8.2.1 & 7.1, ObjectiveCon iOS 10 to 8.0.
在iOS 10 到 8.0上使用Xcode 8.2.1 & 7.1、ObjectiveC进行测试。
? To download the full project, search for SO-3073520in Swift Recipes.
? 要下载完整的项目,请在Swift Recipes 中搜索SO-3073520。
回答by SwiftArchitect
Swift 4
斯威夫特 4
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.
淡化 UILabel(或任何 UIView)的正确方法是使用Core Animation Transition
. 如果内容不变,它不会闪烁,也不会变黑。
A portable and clean solution is to use a Extension
in Swift (invoke prior changing visible elements)
一个可移植且干净的解决方案是Extension
在 Swift 中使用 a (调用之前更改的可见元素)
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
Invocation looks like this:
调用如下所示:
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
? Find this solution on GitHuband additional details on Swift Recipes.
? 在GitHub 上找到此解决方案,在Swift Recipes上找到更多详细信息。
回答by Mapedd
since iOS4 it can be obviously done with blocks:
从 iOS4 开始,它显然可以用块来完成:
[UIView animateWithDuration:1.0
animations:^{
label.alpha = 0.0f;
label.text = newText;
label.alpha = 1.0f;
}];
回答by Muhammad Asyraf
UILabel Extension Solution
UILabel 扩展方案
extension UILabel{
func animation(typing value:String,duration: Double){
let characters = value.map { uiLabel.textWithAnimation(text: "text you want to replace", duration: 0.2)
}
var index = 0
Timer.scheduledTimer(withTimeInterval: duration, repeats: true, block: { [weak self] timer in
if index < value.count {
let char = characters[index]
self?.text! += "\(char)"
index += 1
} else {
timer.invalidate()
}
})
}
func textWithAnimation(text:String,duration:CFTimeInterval){
fadeTransition(duration)
self.text = text
}
//followed from @Chris and @winnie-ru
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
Simply Called function by
简单调用函数
// Usage: insert view.fadeTransition right before changing content
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
Thanks for all the tips guys. Hope this will help in long term
感谢所有的提示家伙。希望这将有助于长期
回答by winnie-ru
Swift 4.2 version of SwiftArchitect's solution above (works great):
上面 SwiftArchitect 解决方案的 Swift 4.2 版本(效果很好):
// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
Invocation:
调用:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Car"
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func toggle(_ sender: UITapGestureRecognizer) {
let animation = {
self.label.text = self.label.text == "Car" ? "Plane" : "Car"
}
UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve, animations: animation, completion: nil)
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
回答by Imanou Petit
With Swift 5, you can choose one of the two following Playground code samples in order to animate your UILabel
's text changes with some cross dissolve animation.
使用 Swift 5,您可以选择以下两个 Playground 代码示例之一,以便UILabel
通过一些交叉溶解动画来为您的文本更改设置动画。
#1. Using UIView
's transition(with:duration:options:animations:completion:)
class method
#1. usingUIView
的transition(with:duration:options:animations:completion:)
类方法
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
let label = UILabel()
let animation = CATransition()
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Car"
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
// animation.type = CATransitionType.fade // default is fade
animation.duration = 2
view.backgroundColor = .white
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
view.addGestureRecognizer(tapGesture)
}
@objc func toggle(_ sender: UITapGestureRecognizer) {
label.layer.add(animation, forKey: nil) // The special key kCATransition is automatically used for transition animations
label.text = label.text == "Car" ? "Plane" : "Car"
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
#2. Using CATransition
and CALayer
's add(_:forKey:)
method
#2. 使用CATransition
andCALayer
的add(_:forKey:)
方法
UIView.transitionWithView(self.view, duration: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
self.sampleLabel.text = "Animation Fade1"
}, completion: { (finished: Bool) -> () in
self.sampleLabel.text = "Animation Fade - 34"
})
回答by A.G
Swift 2.0:
斯威夫特 2.0:
UIView.animateWithDuration(0.2, animations: {
self.sampleLabel.alpha = 1
}, completion: {
(value: Bool) in
self.sampleLabel.alpha = 0.2
})
OR
或者
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}
回答by Chris
Swift 4.2 solution (taking 4.0 answer and updating for new enums to compile)
Swift 4.2 解决方案(采用 4.0 答案并更新以编译新枚举)
##代码##