简体   繁体   English

NSTimer仅在第一次工作(快速)

[英]NSTimer work only the first time (Swift)

I don't know why my timer working only the first time, this is the code: When I press "timergo" button it work but when it finish and repress the button it doesn't work. 我不知道为什么我的计时器仅在第一次工作,这是代码:当我按下“ timergo”按钮时,它可以工作,但是当我按下并按下按钮时,它就无法工作。

@IBAction func timergo(sender: AnyObject) {      
          startTimer()
    }

    var timer:NSTimer!
    var timerVal:Int = 5

    func startTimer()
    {       
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0
            , target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
    }

    func updateTimer(dt:NSTimer)
    {
        timerVal--

        if timerVal==0{               
            println("FINISH")
        }else if timerVal < 0{
            timer.invalidate()
            //Stop
        } else{
           justTime.text = String(timerVal)
            println("\(timerVal)")
        }   
    }

You need to reset the timerVal when you press the button. 按下按钮时,您需要重置timerVal。 When you start it for the second time, timerVal is still < 0 so it directly goes to invalidate. 第二次启动时,timerVal仍<0,因此直接变为无效。

timerVal is 5 when you push the button the first time; 第一次按下该按钮时, timerVal为5; it is less than 0 the second time. 第二次小于0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM