How can I make a countdown with NSTimer?

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

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

相关标签:
15条回答
  • 2020-11-30 03:55

    Swift 4

    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
    

    Update function

    @objc func updateTime(){
        debugPrint("jalan")
    }
    
    0 讨论(0)
  • 2020-11-30 03:57
    import UIKit
    
    class ViewController: UIViewController {
    
        let eggTimes = ["Soft": 300, "Medium": 420, "Hard": 720]
        
        var secondsRemaining = 60
    
        @IBAction func hardnessSelected(_ sender: UIButton) {
            let hardness = sender.currentTitle!
    
            secondsRemaining = eggTimes[hardness]!
    
            Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:
                #selector(UIMenuController.update), userInfo: nil, repeats: true)
        }
        @objc func countDown() {
             if secondsRemaining > 0 {
                 print("\(secondsRemaining) seconds.")
                secondsRemaining -= 1
            
             }
        }
    }
    
    0 讨论(0)
  • Swift 3

    private let NUMBER_COUNT_DOWN   = 3
    
    var countDownLabel = UILabel()
    var countDown = NUMBER_COUNT_DOWN
    var timer:Timer?
    
    
    private func countDown(time: Double)
    {
        countDownLabel.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
        countDownLabel.font = UIFont.systemFont(ofSize: 300)
        countDownLabel.textColor = .black
        countDownLabel.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
    
        countDownLabel.textAlignment = .center
        self.view.addSubview(countDownLabel)
        view.bringSubview(toFront: countDownLabel)
    
        timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true)
    }
    
    func updateCountDown() {
        if(countDown > 0) {
            countDownLabel.text = String(countDown)
            countDown = countDown - 1
        } else {
            removeCountDownLable()
        }
    }
    
    private func removeCountDownLable() {
        countDown = NUMBER_COUNT_DOWN
        countDownLabel.text = ""
        countDownLabel.removeFromSuperview()
    
        timer?.invalidate()
        timer = nil
    }
    
    0 讨论(0)
提交回复
热议问题