How can I make a countdown with NSTimer?

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

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

15条回答
  •  悲哀的现实
    2020-11-30 03:39

    Swift4

        @IBOutlet weak var actionButton: UIButton!
        @IBOutlet weak var timeLabel: UILabel!
        var timer:Timer?
        var timeLeft = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTimer()
    }
    
    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
    }
    
    @objc func onTimerFires() {
        timeLeft -= 1
        timeLabel.text = "\(timeLeft) seconds left"
    
        if timeLeft <= 0 {
            actionButton.isEnabled = true
            actionButton.setTitle("enabled", for: .normal)
            timer?.invalidate()
            timer = nil
        }
    }
    
    @IBAction func btnClicked(_ sender: UIButton) {
        print("API Fired")
    }
    

提交回复
热议问题