How can I make a countdown with NSTimer?

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

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

15条回答
  •  一向
    一向 (楼主)
    2020-11-30 03:43

    In Swift 5.1 this will work:

    var counter = 30
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    
    
    
    @objc func updateCounter() {
        //example functionality
        if counter > 0 {
            print("\(counter) seconds to the end of the world")
            counter -= 1
        }
    }
    

提交回复
热议问题