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
StatepropertyselectedDatethat will keep track of the date selected by the user. TheStateproperty wrapper tells SwiftUI to redraw the view whenever the value changes. You initialize it with the current date. - You display the
selectedDatein aTextview. You’re using string interpolation to include the selected date in the text. - Next, you add a
DatePickerview. The first parameter is a label that screen readers will read to users. Theselection:parameter binds theDatePickerto theselectedDatestate property you created earlier. ThedisplayedComponents:parameter specifies that you only want to display the date, not the time. Finally, you set the style to.graphicalwhich 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.