简体   繁体   English

在NSTimer中增加时间

[英]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. 我正在创建一个iOS测试游戏作为练习,希望在15秒计时器结束时运行一次游戏结束方法。

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. 到目前为止,我在viewDidLoad使用了计时器,并使用了一种具有一些条件格式的方法,该方法将根据用户的操作来执行操作。

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. 创建计时器后,无法更改NSTimer的时间段,只能在请求的时间段之后取消计时器或允许计时器触发。

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. 当该值达到0时,结束游戏。

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. 创建NSTimer ,您将无法更改时间间隔。 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. 您将需要提供很多参数,因为NSTimer不会存储所有参数。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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