SwiftUI_visionOS_Note

DatePicker()

Jan 18, 2024
2 min read|

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)
    }
}
swift

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)
swift

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
DatePicker("Select a Date", selection: $selectDate, displayedComponents: [.date, .hourAndMinute])
swift

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)
        
         }
swift

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])
swift

5. Display the Date() into string

  • We can bring the Date() data into string
Text(selectDate.description)
swift

  • We have to format the date by creating a function
var dateFormatter: DateFormatter{
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }
swift
  1. It creates variable called dateFormatter with DateFormatter{} component
  1. which means, it has to return DateFormatter() by calling formatter
  1. Now, formatter is DateFormatter()
  1. formatter.dateStyle = .short → DateFormatter().dateStyle = .short
  1. return formatter

  • We change the description
Text(selectDate.description).font(.title)
swift

to

Text(dateFormatter.string(from: selectDate)).font(.title)
swift

Subscribe to our newsletter

Get the latest news and updates from our team