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.
You can add sleep function
If you want to keep it all inline you can do this:
define those variables
Place this timer in your view did load or wherever you want to start the label change
and implement this method:
when you want to stop it or change the view controller dont forget to call
You can also use this function to delay something
and usage is :
Hope it will help you.
Marked answer doesn't delay loop iterations and you still get just the last value in the label.text.
You can solve it like this:
Usage:
With
Timer
, you should be careful to callinvalidate
of theTimer
inviewDidDisappear
or else you may not release the view controller.Alternatively, you can use a GCD dispatch timer, in which you completely eliminate the strong reference cycle by using
[weak self]
pattern: