UIDatePicker mode countDownTimer value changed callback not calling first time

Viewed 207

I am having this strange issue in UIDatePicker mode .countdownTimer

enter image description here

When I add constraints of up/down/left/right to the datePicker view, the callback is not registered for the first time. However, if I add only Alignment constraints, the callback works everytime. Maybe its a bug. Any idea why isn't it working?

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        datePicker.datePickerMode = .countDownTimer
        datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)

    }

    @objc func datePickerValueChanged(_ sender: UIDatePicker){
        print("Selected value \(sender.countDownDuration)")
    }
}

2 Answers

OK, it's a long-known bug in iOS, since iOS 7 or so. You can work-around in your case if you put the following somewhere into viewDidLoad:

DispatchQueue.main.async {
    self.datePicker.countDownDuration = self.datePicker.countDownDuration
}

Seems nasty, and is nasty.

The workaround of setting the countDownDuration didn't work for me. Instead the only way I managed to solve this is to replace the UIDatePicker with a UIPickerView and populate it myself with 4 components: hours, "hour(s)" label, mins, "min(s)" label.

  • The hours are 0-23
  • The hours label is a single row component, which gets reloaded when the hours are changed so that it switches to "hour" when it's 1 hour
  • The mins are 0-59
  • The mins label is the same as the hours label
Related