Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Use SwiftUI's DatePicker view to show a calendar-style picker.
Use SwiftUI's DatePicker view to show a calendar-style picker.

Here’s what’s happening in this code:

  • You declare a State property selectedDate that will keep track of the date selected by the user. The State property wrapper tells SwiftUI to redraw the view whenever the value changes. You initialize it with the current date.
  • You display the selectedDate in a Text 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. The selection: parameter binds the DatePicker to the selectedDate state property you created earlier. The displayedComponents: 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.