How can I make a countdown with NSTimer?

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

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

15条回答
  •  青春惊慌失措
    2020-11-30 03:36

    Add this to the end of your code... and call startTimer function with a parameter of where you want to count down to... For example (2 hours to the future of the date right now) -> startTimer(for: Date().addingTimeInterval(60*60*2))

    Click here to view a screenshot of iPhone Simulator of how it'll look

    extension ViewController
    {
        func startTimer(for theDate: String)
        {
            let todaysDate = Date()
            let tripDate = Helper.getTripDate(forDate: theDate)
            let diffComponents = Calendar.current.dateComponents([.hour, .minute], from: Date(), to: tripDate)
            if let hours = diffComponents.hour
            {
                hoursLeft = hours
            }
            if let minutes = diffComponents.minute
            {
                minutesLeft = minutes
            }
            if tripDate > todaysDate
            {
                timer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
            }
            else
            {
                timerLabel.text = "00:00:00"
            }
        }
        
        @objc func onTimerFires()
        {
            secondsLeft -= 1
            
            //timerLabel.text = "\(hoursLeft):\(minutesLeft):\(secondsLeft)"
            timerLabel.text = String(format: "%02d:%02d:%02d", hoursLeft, minutesLeft, secondsLeft)
            if secondsLeft <= 0 {
                if minutesLeft != 0
                {
                    secondsLeft = 59
                    minutesLeft -= 1
                }
            }
            
            if minutesLeft <= 0 {
                if hoursLeft != 0
                {
                    minutesLeft = 59
                    hoursLeft -= 1
                }
            }
            
            if(hoursLeft == 0 && minutesLeft == 0 && secondsLeft == 0)
            {
                timer.invalidate()
            }
            
        }
    }
    

提交回复
热议问题