我正在尝试使用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*
Swift 4
-
加
var timer = Timer()
到班级的顶端
-
设置您的计时器(使用您的原始信息 - 您可能需要根据一些建议进行更改,尤其是@Rob中关于帧速率的建议)
timer = Timer.scheduledTimer(timeInterval: 0.003, target: self, selector: #selector("openFrameAnimation"), userInfo: nil, repeats: true)
-
停止计时器
timer.invalidate() timer = Timer()
检查并确保没有连续多次创建计时器。这可能会导致对原始计时器的引用丢失。
在创建计时器之前执行此操作会有所帮助。
guard timer == nil else {
return
}