如何使用“NSTimer”停止拍摄

时间:2015-08-21 23:36:16

标签: ios swift nstimer

我有一个人物拍摄,一旦你触摸屏幕它就会一直亮着,但我希望它在你停止触摸屏幕时停止。现在,当您触摸屏幕时,它将开始拍摄,但是当您停止触摸屏幕时它不会停止。

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        player.position.x = location.x
        var timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("spawnShot"), userInfo: nil, repeats: true)
    }
}

override func touchesEnded(touches: Set<NSObject>, withEvent: UIEvent){
    for touch: AnyObject in touches{
        var timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("spawnShot"), userInfo: nil, repeats: false)
    }
}

1 个答案:

答案 0 :(得分:1)

要停止重复计时器,您需要使其无效,为此将timer保留为属性,然后在touchesBegan中进行计划,如果您想要停止计时器,则在您的情况下使其touchesEnded无效1}}方法,你可以这样invalidate计时器。

if self.timer.valid
        {
            self.timer.invalidate()
            self.timer = nil
        }