func setOverlayTitle() {
self.overlayLogo!.text = "Welcome"
var hello: [String] = ["Bon Jour", "GUTEN\nMORGEN", "BONJOUR", "HOLA", "안녕하세요", "BUENOS DÍAS", "BUONGIORNO", "早安", "おはよう", "गुड मॉर्निंग"]
for (var i = 1; i < hello.count-1; i++) {
UIView.animateWithDuration(1.0, delay: 2.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.overlayLogo!.alpha = 0.0
}, completion: {
(finished: Bool) -> Void in
println(i)
self.overlayLogo!.text = hello[i]
// Fade in
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.overlayLogo!.alpha = 1.0
}, completion: nil)
})
}
}
我有以下代码,我正在尝试遍历数组“hello”,同时延迟 2 秒淡入/淡出标签。但是这段代码行不通! 目前它只打印数字 9, 9 次并且只淡入/淡出一次
最佳答案
问题是由您在那里使用的 for
循环引起的。您无法以这种方式获得所需的行为。 for
循环不会等待标签动画完成后再开始下一次迭代。取而代之的是,您可以在每个动画周期完成后从方法本身进行递归调用。
您需要在您的类中声明一个变量并实现如下方法:
Swift 5 及更高版本的更新:
var iterator = 1;
override func viewDidLoad() {
super.viewDidLoad()
self.lblAnime!.text = "Welcome"
setOverlayTitle()
}
func setOverlayTitle() {
let hello: [String] = ["Bon Jour", "GUTEN\nMORGEN", "BONJOUR", "HOLA", "안녕하세요", "BUENOS DÍAS", "BUONGIORNO", "早安", "おはよう", "गुड मॉर्निंग"]
UIView.animate(withDuration: 1.0, delay: 2.0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.lblAnime!.alpha = 0.0
}, completion: { (finished: Bool) -> Void in
self.lblAnime!.text = hello[self.iterator]
// Fade in
UIView.animate(withDuration: 1.0, delay: 0.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.lblAnime!.alpha = 1.0
}, completion: { (finished: Bool) -> Void in
self.iterator += 1
if self.iterator < hello.count {
self.setOverlayTitle();
}
})
})
}
原始答案(旧版本的 Swift):
var iterator = 1;
override func viewDidLoad()
{
super.viewDidLoad()
self.lblAnime!.text = "Welcome"
setOverlayTitle()
}
func setOverlayTitle()
{
var hello: [String] = ["Bon Jour", "GUTEN\nMORGEN", "BONJOUR", "HOLA", "안녕하세요", "BUENOS DÍAS", "BUONGIORNO", "早安", "おはよう", "गुड मॉर्निंग"]
UIView.animateWithDuration(1.0, delay: 2.0, options: UIViewAnimationOptions.CurveEaseOut, animations:
{
self.lblAnime!.alpha = 0.0
},
completion:
{(finished: Bool) -> Void in
println(self.iterator)
self.lblAnime!.text = hello[self.iterator]
// Fade in
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations:
{
self.lblAnime!.alpha = 1.0
},
completion:
{(finished: Bool) -> Void in
self.iterator++
if self.iterator < hello.count
{
self.setOverlayTitle();
}
})
})
}
关于ios - 使用数组中的字符串淡入/淡出标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443739/