swiftuikituidatepicker

New UIDatePicker as inputView


With iOS 13 and earlier we could use UIDatePicker as inputView but what now ?

I tried with ios14 and nothing append when the textfield is tapped.

var timePicker = UIDatePicker()
self.timePicker.preferredDatePickerStyle = UIDatePickerStyle.wheels
self.timePicker.datePickerMode = UIDatePicker.Mode.time
self.timePicker.minuteInterval = 5
self.startTimeTxtField.inputView = self.timePicker

Is it normal ?


Solution

  • Apparently, this is currently a known issue. the workaround is to call sizeToFit on the date picker before assigning it as input view.

    Swift

    let datePicker = UIDatePicker()
    datePicker.datePickerMode = .time
    datePicker.locale = .current
    if #available(iOS 14, *) {
        datePicker.preferredDatePickerStyle = .wheels
        datePicker.sizeToFit()
    }
    textField.inputView = datePicker
    

    Objective-C

    if (@available(iOS 14.0, *)) {
        [datePicker setPreferredDatePickerStyle:UIDatePickerStyleWheels];
        [datePicker setDatePickerMode:UIDatePickerModeDate]; //optional
        [datePicker sizeToFit];
    }
    

    See here for the answer from apple forum.