-2

I have a UILabel that needs to change its text to the next item in an array after a certain amount of time. I'm using a for-in loop to achieve this. My issue, though, is that the label won't change until the loop is complete, which defeats the purpose. I have done a lot of searching, and it seems as though using dispatch_async(dispatch_get_main_queue()... is the way to do this. I have tried to use it as other people have, but it doesn't update the label's text. So, if someone could help me use it in my code, or has a solution to update the text in the loop, it would be appreciated.

My code:

@IBAction func startEndTouch(sender: AnyObject) {

var wordsPerMinVal:Double = 60.0/sliderValueBen

for item in textEnterGo {
    delay(wordsPerMinVal){
        self.yourWordsLabel.text = item
        print(item)   
    }
}
}

Two places I got some info from:

dslkfjsdlfjl & Rob

Vacawama

Community
  • 1
  • 1
Ben A.
  • 874
  • 7
  • 23
  • You cannot do this in a simple `for` loop. Think about it. The `delay` delays what's inside its curly braces, but it does not delay your code — that is, it does not delay the loop itself. The loop runs at lightning speed, so all your `delay` clauses, which have the same `wordsPerMinVal`, execute more or less simultaneously (but later, of course). – matt Apr 04 '16 at 00:54
  • @matt Thanks for the explanation. Is there any way for my app to be able to work the way I want it to? – Ben A. Apr 04 '16 at 01:01

1 Answers1

2

try it:

var textEnterGo:[String] = ["1","2","3","4","5","6","7","8","9","10"]
var wordsPerMinVal:Double = 0
var timer:NSTimer?
@IBAction func startEndTouch(sender: AnyObject) {
    if timer != nil{
        index = 0
        self.lblText.text = ""
        timer!.invalidate()
        timer = nil
    }
    wordsPerMinVal = 1
    self.timer =   NSTimer.scheduledTimerWithTimeInterval(self.wordsPerMinVal, target: self, selector: #selector(ViewController.setTextForLabel), userInfo: nil, repeats: true)
}

var index:Int = 0
func setTextForLabel(){
    self.lblText.text = self.textEnterGo[index]
    index += 1
    if index > self.textEnterGo.count-1{
        index = 0
    }
}
Nguyen Hoan
  • 1,583
  • 1
  • 11
  • 18