Create a Date Picker in SwiftUI
Written by Team Kodeco
SwiftUI simplifies the process of implementing a date picker in your application. A date picker is a user interface element that lets users pick a date, and sometimes time, through a familiar calendar-like interface. With SwiftUI, this can be done with just a few lines of code. Let’s dive into it.
Here’s the code that encapsulates your date picker:
struct ContentView: View {
@State private var selectedDate = Date()
var body: some View {
VStack {
Text("Selected date is: \(selectedDate)")
DatePicker("Select a date", selection: $selectedDate, displayedComponents: .date)
.datePickerStyle(.graphical)
.padding()
}
.padding()
}
}
Your preview should look like this:
Here’s what’s happening in this code:
- You declare a
State
propertyselectedDate
that will keep track of the date selected by the user. TheState
property wrapper tells SwiftUI to redraw the view whenever the value changes. You initialize it with the current date. - You display the
selectedDate
in aText
view. You’re using string interpolation to include the selected date in the text. - Next, you add a
DatePicker
view. The first parameter is a label that screen readers will read to users. Theselection:
parameter binds theDatePicker
to theselectedDate
state property you created earlier. ThedisplayedComponents:
parameter specifies that you only want to display the date, not the time. Finally, you set the style to.graphical
which displays a calendar-style date picker.
Running this code will show a date picker on the screen, allowing the user to select a date from a calendar view. The selected date will be displayed above the picker.
It’s as simple as that to add a date picker to your SwiftUI application! This is a very basic setup, but you can customize it further to suit the needs of your specific application.