Search code examples
swiftuidatepicker

Set maximum time of UIDatePicker in countDownTimer mode


I am new to swift and I'm trying to have a picker to select the frequency of notifications. I want to set the max amount the user can pick to be 2 hours, but what I'm doing is not working anyone knows if this is possible?

This is what i have done:

let minutePicker = UIDatePicker()
minutePicker.datePickerMode = .countDownTimer
minutePicker.minuteInterval = 10 //sets the interval of minutes.
minutePicker.countDownDuration = 30*60 //set starting value.
minutePicker.maximumDate = Date(timeInterval: 60*60*2, since: Date())

Solution

  • You could do something like this:

       let minutePicker = UIDatePicker()
        minutePicker.datePickerMode = .countDownTimer
        minutePicker.addTarget(self, action: #selector(respondToChanges(picker:)), for: .valueChanged)
        minutePicker.minuteInterval = 10
    
        var components = DateComponents()
        components.minute = 30
        let date = Calendar.current.date(from: components)!
        minutePicker.setDate(date, animated: true)
    

    Then you have to create a respondToChanges method. A possible implementation would look like this:

    @objc
    func respondToChanges(picker: UIDatePicker) {
        if (picker.countDownDuration > 7200) { //countDownDuration has to be in seconds
            var components = DateComponents()
            components.hour = 2
            let date = Calendar.current.date(from: components)!
            picker.setDate(date, animated: true)
        }
    }
    

    The documentation says: "The minimum and maximum dates are ignored in the countdown-timer mode". So with my solution you set the time manually back to 2 hours, each time the user select more than 2 hours.