SwiftStarter SwiftStarter - 3 months ago 8
Swift Question

NSTimer to Change Text

Sorry if this is a really basic questions, but I can’t seem to work it out, so I thought I would ask the experts.

I’ve got a timer for my project that counts down and updates a label according to what is stored in an array.

var array : String[]()

var x = 0


@IBAction func playBtnPressed(sender: UIButton)
{

timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(PlayVC.update), userInfo: nil, repeats: true)

}

func update()
{
if x < array.count {

let item = array[x]

aLbl.text = array.itemTitle

x += 1
}

}


My problem is that the text is only updated after the first countdown and 60 seconds is a long time to wait lol.
I would actually like the first String in my array to appear as soon as the button is tapped.
Is there a way to set the text at the very beginning of the countdown?
Thank you for your help :)

Answer

So you want to update a label every minute. And you also want to update it immediately after the button is pressed. Hopefully I didn't misunderstand the question.

It's actually as easy as adding this line before the timer = NSTimer ... line:

update()

Note that your current code can cause two or more timers to be created and run when the button is pressed more than once. You might not want this.

To stop the timer when the button is pressed a second time, do this:

if timer == nil {
    timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(PlayVC.update), userInfo: nil, repeats: true)
} else {
    timer.invalidate()
    timer = nil
}

To do nothing when the button is pressed a second time jus remove the else part.