快速为for循环添加延迟 [英] Add a delay to a for loop in swift
问题描述
我有一个编码问题".
我有一个标签,我想每2秒动态更改一次该文本. 我已完成以下操作:
I have a label, which text I want to change dynamically every 2 seconds. I've done the following:
// WELCOME STRING ARRAY
let welcomeContainer:[String] = ["Welcome","Benvenuti","Bienvenue","Willkommen","üdvözlet","Dobrodošli","добро пожаловать","Witajcie","Bienvenido","Ласкаво просимо","Vitajte","欢迎你来"]
,然后,而不是使用timerwithinterval
(对于这个简单的任务来说似乎太多了),我尝试在for
循环中的函数中使用delay
方法:
and then, rather than using a timerwithinterval
(which seemed to be too much for this simple task), I tried with the delay
method in my function inside for
loop:
func welcomeLabelChange() {
for i in 0..<welcomeContainer.count {
welcomeLabel.text = welcomeContainer[i]
delay(delay: 2.0, closure: {})
}
不幸的是,它完全跳过了延迟... for循环立即执行,仅显示数组中的最后一个文本. 我在做什么错了?
Unfortunately it's entirely skipping the delay... the for loop is executed instantly and just the last text in the array is displayed. What am I doing wrong?
我找到了这个 OBJ-C答案,但是这表明(旧的)NSTimer
实现.
I found this OBJ-C answer, but it's suggesting an (old) NSTimer
implementation.
推荐答案
您还可以使用此功能延迟某些时间
You can also use this function to delay something
//MARK: Delay func
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
,用法是:
delay(2) //Here you put time you want to delay
{
//your delayed code
}
希望它会对您有所帮助.
Hope it will help you.
这篇关于快速为for循环添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!