How to make a countdown to date Swift

前端 未结 4 493
青春惊慌失措
青春惊慌失措 2021-02-03 16:03

I was facing the struggle of making a timer app, so I thought that now that I solved it I could help others who face the problem. So basically this app counts down to a specific

4条回答
  •  暖寄归人
    2021-02-03 16:52

    Cleaned up and updated with countdown computed on a timer and leading zero String format.

        let futureDate: Date = {
            var future = DateComponents(
                year: 2020,
                month: 1,
                day: 1,
                hour: 0,
                minute: 0,
                second: 0
            )
            return Calendar.current.date(from: future)!
        }()
    
        var countdown: DateComponents {
            return Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: futureDate)
        }
    
        @objc func updateTime() {
            let countdown = self.countdown //only compute once per call
            let days = countdown.day!
            let hours = countdown.hour!
            let minutes = countdown.minute!
            let seconds = countdown.second!
            countdownLabel.text = String(format: "%02d:%02d:%02d:%02d", days, hours, minutes, seconds)
        }
    
        func runCountdown() {
            Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        }
    

提交回复
热议问题