![](/img/trans.png)
[英]Repeat Fade In / Fade Out Between Two Different Texts On Same UILabel
[英]how can I fade in and out different texts on the same UILabel in Swift?
目前,我在swift
有一个字符串数组,并且正在UILabel
上循环显示它们:
let greetings = ["Test1", "Test2", "Test3", "Test4"]
override func viewDidLoad(){
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(TutorialEntryPoint.update), userInfo: nil, repeats: true)
}
var i = 0
func update() {
if(i==4){
i=0
}
myLabel.text = greetings[i]
i += 1
}
可以,但是每个文本都会消失并突然显示-是否可以通过修改方式使每个文本平滑地消失/显示? 我考虑过使用animateWithDuration
和修改alpha
,但是我不确定如何正确地做。
您可以像这样在标签上设置文本动画
UIView.transition(with: label,
duration: 0.25,
options: [.transitionCrossDissolve],
animations: {
label.text = "Your Text"
}, completion: nil)
可以尝试这样的事情
//inside viewDidLoad
let animation = CAKeyframeAnimation()
animation.keyPath = "opacity"
animation.values = [0, 1, 1, 0]
animation.keyTimes = [0, 0.1, 0.9, 1]
animation.duration = 2.0 //same as your timer
animation.repeatCount = Float.infinity
myLabel.layer.addAnimation(animation, forKey: "fade")
尚未测试过,因此可能需要进行一些调整,但是我在执行此操作之前先使用了类似的方法来淡入和淡出某些内容
在几天的过程中,我尝试了几种方法,而我发现的最佳解决方案是在这里: https : //medium.com/ios-os-x-development/swift-3-so-i-wanted-to -animate-a-label-14dd2b332ef9
必须更改变量和函数以说明String
类型,而不是Int
。 我使用的是字符串数组(如此处的问题),所以我在第131行的setTextValue
之后增加了一个索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.