2014-12-04 51 views
1

所以我每秒增加一個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()但這只是做什麼工作,計時器不會重新啓動

+0

「並且定時器不會重新啓動」當然。無效的計時器不能重複使用;它永遠是死的。 – matt 2014-12-04 02:05:31

+0

這不就是某種動畫嗎?計時器是動畫製作最糟糕的方式。如果你想動畫,使用實際的動畫!它內置在iOS中。 – matt 2014-12-04 02:06:31

+0

好的。我將如何「動畫」將CGPoint y值每秒增加一定量? – 24GHz 2014-12-04 02:12:20

回答

1

你的問題是錄播,你必須創建一個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是動畫對象,使用核心動畫,而不是一個好辦法。

+0

老兄,謝謝!使用的解決方案2,並完美地工作。不斷學習迅速,所以解決的每一個問題都會有所幫助!希望這也能解決其他有類似問題的人的問題 – 24GHz 2014-12-04 02:45:07

+0

順便說一句,你將如何使用核心動畫來解決這個問題?也很好知道 – 24GHz 2014-12-04 02:47:50