Creating Date and Time Pickers in SwiftUI: Dropdown Wheel and Calendar Style

The DatePicker allows users to set a particular date using a scrolling wheel. With SwiftUI 2, you also get access to the GraphicalDatePickerStyle() which displays a calendar as well as time.

How to let users pick a date and time using a dropdown wheel or a calendar style.

DatePicker

First, set your date as a state. This date picker is bound to a selectedDate property. Users can choose any date up till the current date.

struct ContentView: View {
	@State var selectedDate = Date()

  var body: some View {
		DatePicker("Date", selection: $selectedDate)
	}
}

..

Date Picker Wrapper 

You can customize your UI more by wrapping around a Text or an Image.

DatePicker(selection: $selectedDate) {
	Text("Select a date")
		.font(.title3)
}

..

Date Range 

The ...Date() allows the user to select any date until the present day. 

DatePicker("Range", selection: $selectedDate, in: ...Date())

Alternatively, you can set it to starting from the present date with Date()....

DatePicker("Range", selection: $selectedDate, in: Date()...)

..

Time Picker 

Instead of a specific date, you can decide to let users select the hours and minutes.

DatePicker("Time", selection: $selectedDate, displayedComponents: .hourAndMinute)

..

Date and Time 

You can combine both date and hourAndMinute by using an array.

DatePicker("Date and time", selection: $selectedDate, displayedComponents: [.date, .hourAndMinute])

..

Picking Date and Time 

We can combine both the date and the time.

DatePicker("Date and Time Picker", 
		selection: $selectedDate, displayedComponents: [.date, .hourAndMinute])

..

GraphicalDatePickerStyle() 

GraphicalDatePickerStyle() lets you show the full calendar user interface immediately instead of showing the modal on tap.

DatePicker("Select date", selection: $selectedDate)
	.datePickerStyle(GraphicalDatePickerStyle())

..



Comments