如何使用其他NSTimer停止NSTimer?

时间:2015-12-31 16:40:51

标签: ios swift nstimer

注意:我在这个项目中使用swift。

我正在处理我的第一个项目,如果在一定时间后没有按下按钮,我试图停止(无效)NSTimer。我找到了其他方法来阻止我的NSTimer,但没有人说如何在一段时间后停止它,如果按钮实际 按下则重置该时间。阅读所有内容以便更清楚地理解。

现在是我的代码;

@IBOutlet var Text: UILabel!
var timer: NSTimer!
var countdown: Int = 0

@IBAction func StartGame(sender: AnyObject) {
self.countdown = 20
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateCountdown", userInfo: nil, repeats: true)
}

func updateCountdown() {

    self.countdown--

    if self.countdown == 0 {
        self.timer.invalidate()
        self.timer = nil
    }

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

@IBAction func PlayerbuttonPRESSED(sender: AnyObject) {
if Text.text == "Test" {
//Something happens
}
if Text.text == "Testing" {
//Something happens 
}

我最想知道的是,如果在更改ColorText.text之前按下 按钮,我会发生其他事情! (如果在1.5秒后更改文本之前按下按钮)。

聚苯乙烯。对不起,长码,我觉得有必要。 : - )

1 个答案:

答案 0 :(得分:0)

有不同的方法可以做到这一点。一种方法,你可以在按下按钮时将bool值设置为true,然后在updateCountdown中检查布尔值。

例如:

func updateCountdown() {

     self.countdown--

    if self.countdown == 0 && YOUR_BUTTON_BOOL {
        self.timer.invalidate()
        self.timer = nil
    }  

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

但是,以这种方式使用NSTimer会在短时间内触发,例如1.5秒,这可能会变得不准确。定时器触发20次后,过去的时间将大于30秒。如果准确性很重要,那么设置第二个计时器30秒可能会更好。如果按下该按钮,如果30秒计时器触发它,则使30秒计时器无效。