SwiftUI Date Picker Tutorial

In SwiftUI The date picker provides ancustom Picker View that uses multiple rotating wheels to allow users to select dates and times. In this tutorial a future date is selected from the picker view and is presented onscreen. SwiftUI requires Xcode 11 and MacOS Catalina, which can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIDatePickerTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    
    // 1.
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }

    // 2.
    @State private var selectedDate = Date()
    
   
    var body: some View {
        VStack {
            Text("Select a future date").font(.largeTitle)
            
            // 3.
            DatePicker(selection: $selectedDate, in: Date()..., displayedComponents: .date) {
                Text("")
            }.padding(30)
            
            // 4.
            Text("Selected Date is \(selectedDate, formatter: dateFormatter)")
                .font(.title)
        }
    }
}
  1. A date formatter is created, which will display the date in the long format. For example “1 Jan 2020”.

  2. A state property is declared which will represent the selected date in the date picker.

  3. The date picker is displayed, only future dates can be selected

  4. The selected date from the picker view is displayed.

Go to the preview window. Click live preview and change the date. The printed text will change also.

The source code of the SwiftUIDatePickerTutorial can be downloaded at the ioscreator repository on Github.