Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a delay to a for loop in swift

I have a coding 'issue'.

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","欢迎你来"]

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: {})
}

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?

I found this OBJ-C answer, but it's suggesting an (old) NSTimer implementation.

like image 600
Alex Avatar asked Sep 30 '16 08:09

Alex


3 Answers

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)
}

and usage is :

        delay(2)  //Here you put time you want to delay
{
            //your delayed code
        }

Hope it will help you.

like image 142
0ndre_ Avatar answered Nov 20 '22 12:11

0ndre_


define those variables

var i = 0
let timer : Timer?

Place this timer in your view did load or wherever you want to start the label change

   timer =  Timer.scheduledTimer(timeInterval: 2.0, target: self, selector:#selector(YourViewController.changeText), userInfo: nil, repeats: true)

and implement this method:

func changeText(){
    if i>=welcomeContainer.count {
        i = 0
    }

    welcomeLabel.text = welcomeContainer[i]
    i += 1
}

when you want to stop it or change the view controller dont forget to call

timer.invalidate()
like image 6
ben Avatar answered Nov 20 '22 12:11

ben


You can add sleep function

for i in 0..<welcomeContainer.count {
    welcomeLabel.text = welcomeContainer[i]
    sleep(2) // or sleep(UInt32(0.5)) if you need Double
}
like image 5
Booharin Avatar answered Nov 20 '22 11:11

Booharin