UIDatePicker for iOS13 and above and below iOS13

2.4k Views Asked by At

Implemented UIDatePicker for iOS14 supported but needs support for iOS 12 as well. How to implement the same for iOS12 as well. Below is my code:

datePicker = UIDatePicker.init()
        datePicker.backgroundColor = UIColor.white
    datePicker.maximumDate = Date()
        datePicker.autoresizingMask = .flexibleWidth
        datePicker.datePickerMode = .date
    if #available(iOS 13.4, *) {
        datePicker.preferredDatePickerStyle = .compact
    } else {
        // Fallback on earlier versions
        
    }
        datePicker.addTarget(self, action: #selector(self.dateChanged(_:)), for: .valueChanged)

Error in iOS12:

preferredDatePickerStyle' is only available in iOS 13.4 or newer

What to implement under check below iOS 13?

3

There are 3 best solutions below

2
Krunal Nagvadia On

Under the iOS 13 you can use automatic.

if #available(iOS 13.4, *) {
        datePicker.preferredDatePickerStyle = .compact
    } else {
        // Fallback on earlier versions
        datePicker.preferredDatePickerStyle = .automatic
    }
1
Tarun Tyagi On

There's no need to specify anything for < iOS 13.4 versions. UIDatePicker will work as it used to in older versions without specifying this value.

If you want to FORCE old iOS 12 style on the new devices iOS 14 or above as well, you can use -

if #available(iOS 13.4, *) {
    datePicker.preferredDatePickerStyle = .wheels
}
0
Hüsamettin Eyibil On

Unfortunately, for under iOS 13.4 you don't have another option to choose. You can only use UIDatePicker with .wheels style.

In order to choose a style, you must have a version of at least iOS 13.4. (iOS 14.0 for .inline style)

You can use .wheels for lower versions. But you might have to redesign your UI.

On the other hand, you can use third-party date components or create your own date component to provide consistency between versions.