多个NSTimers Xcode 6 Swift
问题描述:
所以我每秒增加一个CGPoint
的y值。要做到这一点,我正在使用NSTimer
,它会触发某个增加y值的函数。问题是我每次用户触摸显示器时都会增加y值。我注意到每次有人点击时,都会有多个定时器发射,因此增加的y值比想要的要多。那么如何删除以前的NSTimers并只使用最后一个呢?多个NSTimers Xcode 6 Swift
我目前NSTimer
设置
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var timer: NSTimer?
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
还有更多的我的代码,但是这个基本NSTimer
设置一个触发处做的y值增加“更新”。
我想这样做timer.invalidate()
但这只是做什么工作,计时器不会重新启动
答
你的问题是录播,你必须创建一个NSTimer
例如每次用户,而你没有删除最后一个`的NSTimer实例,所以每个创建的实例都在runloop中运行。
解决方案1:
var timer: NSTimer!
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if(timer == nil) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
}
解决方案2:
var timer: NSTimer!
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if(timer != nil) {
timer.invalidate()
timer = nil
}
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
顺便说一句:我不认为使用NSTimer
是动画对象,使用核心动画,而不是一个好办法。
“并且定时器不会重新启动”当然。无效的计时器不能重复使用;它永远是死的。 – matt 2014-12-04 02:05:31
这不就是某种动画吗?计时器是动画制作最糟糕的方式。如果你想动画,使用实际的动画!它内置在iOS中。 – matt 2014-12-04 02:06:31
好的。我将如何“动画”将CGPoint y值每秒增加一定量? – 24GHz 2014-12-04 02:12:20