The DatePicker is a native SwiftUI component for selecting date and/or time.
You can implement it using various initializers and customize it with different DatePickerStyles.
Additionally, a DateFormatter can be used to effectively display dates in your visionOS application.
1. Choose DatePicker
- Select the on with title & selection parenthesis (most general)
- Bind the today’s date variable
struct ContentView: View {
@State var selectDate: Date = Date()
var body: some View {
DatePicker("Select a Date", selection: $selectDate)
}
}
2. Stylize the component
.tint()
isn’t working in DatePicker
.datePickerStyle()
has three styles: compact, graphical, wheel
DatePicker("Select a Date", selection: $selectDate)
.datePickerStyle(.automatic)
3. Select displayed component
- Select the one with title, selection, displayComponents
- We can choose which components will show with
[.date, .hourAndMinute]
- Can delete
.date
to only show.hourAndMinute
and vice versa
- Can delete
DatePicker("Select a Date", selection: $selectDate, displayedComponents: [.date, .hourAndMinute])
4. Add Closed Range
- Select the one with
in: ColsedRange<Date>
.
- Create a Date let with starting from year 2018 to Today
@State var selectDate: Date = Date()
let startingDate: Date = Calendar.current.date(from: DateComponents(year: 2018)) ?? Date()
let endingDate: Date = Date()
var body: some View {
DatePicker("Select a Date", selection: $selectDate, in: startingDate...endingDate)
.datePickerStyle(.automatic)
}
4.1 Edit the display component
- Add
displayedComponents: [.date, .hourAndMinute]
to edit the diplay
DatePicker("Select a Date", selection: $selectDate, in: startingDate...endingDate, displayComponents: [.date])
5. Display the Date() into string
- We can bring the Date() data into string
Text(selectDate.description)
- We have to format the date by creating a function
var dateFormatter: DateFormatter{
let formatter = DateFormatter()
formatter.dateStyle = .short
return formatter
}
- It creates variable called dateFormatter with
DateFormatter{}
component
- which means, it has to return
DateFormatter()
by calling formatter
- Now, formatter is DateFormatter()
- formatter.dateStyle = .short → DateFormatter().dateStyle = .short
- return formatter
- We change the description
Text(selectDate.description).font(.title)
to
Text(dateFormatter.string(from: selectDate)).font(.title)