How can I make a countdown with NSTimer?

后端 未结 15 1668
遇见更好的自我
遇见更好的自我 2020-11-30 03:17

How can I make a countdown with an NSTimer using Swift?

15条回答
  •  鱼传尺愫
    2020-11-30 03:36

    Swift 5 another way. Resistant to interaction with UI

    I would like to show a solution that is resistant to user interaction with other UI elements during countdown. In the comments I explained what each line of code means.

     var timeToSet = 0
     var timer: Timer?
    
     ...
    
     @IBAction func btnWasPressed(_ sender: UIButton) {
    
          //Setting the countdown time
          timeLeft = timeToSet
          //Disabling any previous timers.
          timer?.invalidate()
          //Initialization of the Timer with interval every 1 second with the function call.
          timer = Timer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
          //Adding Timer to the current loop
          RunLoop.current.add(timer!, forMode: .common)
    
      }
    
     ...
    
     @objc func countDown() {
    
         if timeLeft > 0 {
             print(timeLeft)
             timeLeft -= 1
         } else {
             // Timer stopping
             timer?.invalidate()
         }
     }
    

提交回复
热议问题