I have a countdown implemented but currently the label assigned to display the value isn't showing the value at all. I've tried print(countdownLabel) to see if it is recording in which the label's properties are returned and not the countdown. Thanks in advance!
class CountdownViewController: UIViewController {
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var countdownLabel: UILabel!
//Countdown
let futureDate: Date = {
let future = DateComponents(
year: 2021,
month: 1,
day: 06,
hour: 09,
minute: 32 ,
second: 45
)
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!
self.countdownLabel.text = String(format: "%02d:%02d:%02d:%02d", days, hours, minutes, seconds)
}
override func viewDidLoad() {
super.viewDidLoad()
func runCountdown() {
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
runCountdown()
(print(countdown))
(print(countdownLabel as Any))
}
}
The problem in your code is, you declared function runCountdown()
inside another function viewDidLoad()
but, you didn't call runCountdown()
afterwards.
override func viewDidLoad() {
super.viewDidLoad()
func runCountdown() {
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
runCountdown()
(print(countdown))
(print(countdownLabel as Any))
}