所以我已经在 Swift 中为标签动画构建了淡入淡出。但我想从一系列不同的句子中淡入和淡出,因此每次淡入和淡出时,都会是不同的五线谱。
override func viewDidLoad()
{
super.viewDidLoad()
label.alpha = 0
animatedText()
}
func animatedText(){
UIView.animateWithDuration(2.0, animations: {
self.label.alpha = 1.0
}, completion: {
(Completed: Bool) -> Void in
UIView.animateWithDuration(1.0, delay: 2.0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.label.alpha = 0
}, completion: {
(Completed: Bool) -> Void in
self.animatedText()
})
})
}
最佳答案
尝试这个功能:
class ViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
var sentences = ["The cat sat.", "The rhino ate.", "The monkey laughed", "The zebra ran.", "The fish swam", "The potato grew."]
override func viewDidLoad() {
super.viewDidLoad()
label1.text = sentences[0]
label2.text = sentences[1]
label1.alpha = 1.0
label2.alpha = 0.0
}
var counter = 1
@IBAction func animateBtnPressed(_ sender: UIButton) {
fadeText(counter: &counter, duration: 2.0)
}
func fadeText(counter: inout Int, duration: TimeInterval) {
if counter < sentences.count {
if counter % 2 != 0 {
UIView.animate(withDuration: duration, animations: {
self.label1.alpha = 0.0
self.label2.alpha = 1.0
}, completion: { finished in
if finished {
counter += 1
if counter <= (self.sentences.count - 1) {
self.label1.text = self.sentences[counter]
} else {
return
}
self.fadeText(counter: &counter, duration: duration)
}
})
} else {
UIView.animate(withDuration: duration, animations: {
self.label1.alpha = 1.0
self.label2.alpha = 0.0
}, completion: { finished in
if finished {
counter += 1
if counter <= (self.sentences.count - 1) {
self.label2.text = self.sentences[counter]
} else {
return
}
self.fadeText(counter: &counter, duration: duration)
}
})
}
}
}
}
假设:
- 有一个名为
sentences
的数组(您可以更改此设置)在ViewController
上其中包含String
- 有一个
counter
从 1 开始 的变量 UILabel
Storyboard中的 s 重叠。
除此之外,您只需使用 counter
调用该函数即可带有 &
的变量前面的运算符,因为 fadeText
更改 counter
变量它需要内存中 counter
的地址变量,而不是值(请注意 inout
参数中的 fadeText
)。
如果您有任何疑问,请随时提问!
关于ios - 我将如何从一系列不同的单词或句子中淡入和淡出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37903504/