如何停止Xcode中的中继器?
问题描述:
好吧,所以我有一个应用程序,当我按下一个按钮时,使用定时器不断振动。我还有另一个我想用来阻止振动的按钮。但也可以通过启动按钮再次启用。我应该怎么做?这里是我的代码(BUTTON2是停止按钮)(也即时通讯使用的Xcode):如何停止Xcode中的中继器?
@IBAction func button1(_ sender: UIButton) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
_ = Timer.scheduledTimer(timeInterval: 0.0, target: self,
selector: Selector(("doaction")), userInfo: nil, repeats: true)
}
@IBAction func button2(_ sender: UIButton) {
}
答
定时器属性添加到您的类:
var timer: Timer?
然后更新您的方法有两种:
@IBAction func button1(_ sender: UIButton) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.0, target: self,
selector: Selector(("doaction")), userInfo: nil, repeats: true)
}
@IBAction func button2(_ sender: UIButton) {
timer?.invalidate()
timer = nil
}
通过使用timer属性,您可以从您的课程中的任何方法访问计时器。
你不能这样做。您没有保留对定时器的任何引用(您将其分配给'_'),因此您无法使其无效。这是一件非常愚蠢的事情。 – matt