Search code examples
swiftxcodeuidatepickerios14

Conversion from iOS 13 UIDatepicker to iOS 14 UIDatepicker


I am currently trying to figure out how to change in code from iOS 13 UIDatePicker to the iOS 14 version with (.wheels). Below you will find a screen shot of the app with the non-functioning date picker and screenshot of the code.

Unfortunately while I am able to understand Swift I am not conversant enough to know where and what changes need to be made so the code will work. I have tried some of the other solutions on here but to no avail. So if anyone could help me that would be great.

I believe I need to change the code for the dateBtnAction, but I have no clue where the new iOS 14 code would go.

@IBAction func datePickerAction(_ sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.dateFormat = "MMM dd, yyyy h:mm a"
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.amSymbol = "am"
    formatter.pmSymbol = "pm"
    // formatter.timeZone = TimeZone(abbreviation: "UTC")!
    // formatter.dateStyle  = .medium
    let dateString = formatter.string(from: sender.date)
    dateBtn.setTitle(dateString, for: .normal)
}

@IBAction func dateBtnAction(_ sender: Any) {
    popupView(forView: datePickerContainerView, viewHeight: 300)
}
Code snippet Result
View Controller snippet of UIDatePicker Image of UIDatePicker on iPhone

Solution

  • just add this code in you viewDidLoad or wherever you setup your datePicker:

    if #available(iOS 13.4, *) {
       yourDatePicker.preferredDatePickerStyle = .wheels
       //yourDatePicker can be in code or IBOutlet
    
    }
    

    according to the documentation these are the styles available (iOS 13.4):

    Styles

    case automatic
    A style indicating that the system picks the concrete style based on the current platform and date picker mode.

    case compact
    A style indicating that the date picker displays as a label that when tapped displays a calendar-style editor.

    case inline
    A style indicating that the date pickers displays as an inline, editable field.

    case wheels
    A style indicating that the date picker displays as a wheel picker.