NSTimer在此函数中失效时不会停止

时间:2016-02-27 22:44:34

标签: swift nstimer

我正在尝试使用NTTimer,但它不起作用。

从这里开始:

timer = NSTimer.scheduledTimerWithTimeInterval(0.003, target: self, selector: "openFrameAnimation", userInfo: nil, repeats: true)

它激发了这个功能:

func openFrameAnimation(){
    Swift.print("Animation Goes... ",NSDate().timeIntervalSince1970)
    self.frame = NSRect(x: self.frame.origin.x,
        y: self.frame.origin.y-12,
        width: self.frame.width,
        height: self.frame.height + 12)
    if(self.frame.height >= self.finalFrame.height){
        Swift.print("STOP")
        self.frame = self.finalFrame
        timer.invalidate()
        // timer = nil //ERROR: nil cannot be assigned to type "NSTimer"
    }
    self.needsDisplay = true
}

即使反复打印“STOP”,计时器仍继续调用openFrameAnimation,我无法阻止它。如果验证条件,我该如何停止计时器?

日志:

[...]
*Animation Goes...  1456613095.27813
STOP
[...]
Animation Goes...  1456613095.51233
STOP
Animation Goes...  1456613095.54458
[...]
STOP
Animation Goes...  1456613095.5938
STOP*

1 个答案:

答案 0 :(得分:8)

Swift 4

  1. 添加

    var timer = Timer()
    
  2. 到班级的顶部

    1. 设置您的计时器(使用原始信息 - 您可能希望根据某些建议进行更改,尤其是来自@Rob的关于帧速率的建议)

      timer = Timer.scheduledTimer(timeInterval: 0.003, target: self, selector: #selector("openFrameAnimation"), userInfo: nil, repeats: true)
      
    2. 停止计时器

          timer.invalidate()
          timer = Timer()