简体   繁体   中英

Adding time to NSTimer

I'm creating an iOS test game as practice and want a game over method to be ran at the end of a 15 second timer.

I also want time to be added to this timer and taken away if certain actions take place.

Not having much luck figuring out how to add time or take away time from a certain timer depending on actions by the user.

So far I have the timer in viewDidLoad and a method with some conditional formatting that will do things depending on what the user does.

Once it has been created, the period of an NSTimer cannot be changed, the timer can only be cancelled or allowed to fire after the requested period.

In order to implement a timer for your game I would suggest that you set up a repeating timer that fires every second. The actual 'time remaining' value is stored in an integer and you decrement this value each time the timer fires. When this value reaches 0, end the game.

This way you can easily add additional time by simply changing the value of the time remaining variable.

This approach also makes it simple to display the remaining time on the screen.

Once NSTimer has been created, you cannot change time interval. But here's method I've done for me:

func addTimeToTimer(timer: NSTimer, time: NSTimeInterval, target: AnyObject, selector: Selector, repeats: Bool) -> NSTimer {
    let currentInterval = Float(timer.timeInterval)
    let targetInterval = NSTimeInterval(currentInterval + Float(time))

    let newTimer = NSTimer.scheduledTimerWithTimeInterval(targetInterval, target: target, selector: selector, userInfo: timer.userInfo, repeats: repeats)

    return newTimer
}

You will need to supply a lot of parameters because NSTimer does not store it all. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM