SwiftStarter SwiftStarter - 3 months ago 23
Swift Question

Nstimer Countdown Skip Button

I'm using nstimer to run code that changes text every 60 seconds.
I was wondering if anyone knew of a way to skip an iteration of the 60 seconds. Say a user doesn't want to read the text currently on display, at the moment they still have to wait 60 seconds.
Is there a way to immediately move on to the next 60 second loop at a button tap?

This is what I have so far:

var array : String[]()

var x = 0


@IBAction func playBtnPressed(sender: UIButton)
{
update()

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
}

}

@IBAction func skipBtnPressed(sender: UIButton)
{

}


Thanks in advance for any guidance you can give me! :)

Answer

In your skipBtnPressed() you should first invalidate the timer, update data and then set another timer. Like this

@IBAction func skipBtnPressed(sender: UIButton)
{
    timer.invalidate()
    update()
    timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(PlayVC.update), userInfo: nil, repeats: true)

}
Comments