69 - Create a Date Picker in SwiftUI

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.

Here’s what’s happening in this code:

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.