New UIDatePicker in iOS 14

Date Picker Compressed.png

Such a beautiful date picker, Apple finally decided to change the way we interact with our UIDatePicker, it’s one of the best things introduced in this year’s WWDC as everyone widely uses it.

I hope you are having a beautiful day. Let’s make it even better by diving-in into our starter project and explore the ways we can use the new UIDatePicker style.

Click Here to download the starter project.

Note: For this tutorial, you will need Xcode 12, at the time of writing this article, Xcode 12 is available as a beta version for download on this link.

Let’s Start

In the starter project, I have already added a UIDatePicker in the Main.storyboard, but it doesn’t look like what we expected.

Date Picker Old.png

This is not what we want, but don’t worry, I’ll fix it.

Open the ViewController.swift file, and in viewDidLoad() function add the code shown below.

override func viewDidLoad() {
    super.viewDidLoad()
    
    //  Will only execute if the system is having iOS 14 or greater
    if #available(iOS 14, *) {
        datePicker.preferredDatePickerStyle = .inline
    }
}

Next, Run the application in your simulator or your device.

Simulator and Xcode Compressed.png

Beautiful!

But wait, many times while developing applications, we don’t need the date picker to be on screen the whole time, we may want to click on a button and pick the date from the picker like before.

Let’s see how we can do this.

//  Will only execute if the system is having iOS 13.4 or greater
if #available(iOS 13.4, *) {
    datePicker.preferredDatePickerStyle = .compact // Replace .inline with .compact
}

That’s it. Now, if you run the application. Your app should function like the one shown below.

Compact Mode Video Gif.gif

It automatically updates the date, so you don’t need to look into the handling of the date object. This is significant relief from those bottom sheets and custom pop-ups.

Click Here to download the final project.

I hope you guys enjoyed reading my article. There’s a lot more to learn together, so subscribe to stay updated about my upcoming articles.

If you have any suggestions or questions, Feel free to connect me on Twitter or Reddit. 😉

SwiftUI - How to use LazyVGrid and LazyHGrid in iOS 14?

How to use UIColorPickerViewController in Swift?