【问题标题】:How Do I Stop A Repeater In Xcode?如何在 Xcode 中停止中继器?
【发布时间】:2017-10-08 23:36:40
【问题描述】:

好的,所以我有一个应用程序,当我按下按钮时,它会使用计时器不断振动。我还有另一个按钮,我想用它来阻止它振动。但也可以使用开始按钮再次启用。我该怎么做?这是我的代码(button2 是停止按钮)(我也在使用 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) {
}

【问题讨论】:

  • 你做不到。您没有保留对 Timer 的任何引用(您将其分配给 _),因此您不能使其无效。那是一件非常愚蠢的事情。

标签: ios swift timer vibration


【解决方案1】:

为你的类添加一个计时器属性:

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 属性,您可以从类中的任何方法访问计时器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多