top of page
Writer's pictureHui Wang

25. SwiftUI: Introducing DatePicker

Today I will show you how to use DatePicker.

DatePicker is similar to UIDatePicker in UIKit and is mainly used to provide a list of dates and times.


Knowledge points:

  • First, add a property of DateFormatter that you will use to format the date and time the user selects and display it in the Text view.

  • Initialize an instance of DateFormatter, and set its date style to .long, which means to display in the order of month, day, and year.

private var dateFormatter: DateFormatter {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    return dateFormatter
}

Next:

  • Add another property and add a @State property wrapper to bind to DatePicker. Then, when the user selects a date, the value of this property will also change synchronously.

@State var selectedDate = Date()

Next:

  • Next, add a DatePicker, bind it to the selectedDate property, and set the component type of DatePicker to .date, which means that only the date list is displayed, not the time list.

DatePicker(selection: $selectedDate, displayedComponents: .date) {
    Text("Date")
}

Next:

  • Add a Text view below the DatePicker to display the date and time selected by the user.

Text("You have chosen: \(selectedDate, formatter: dateFormatter)")

  • Click on a "date" to open the DatePicker

  • Select a day in the pop-up picker

  • Click on the "year" to open the year and month pick panel

  • Select the month of the date

  • Then select the year of the date

  • After completing the date picking, click outside the DatePicker to close it.


Next:

  • Change the type of DatePicker to a date and time type.

  • Limit the selection of DatePicker.

  • The minimum value is today.

  • The maximum value is 7 days from today.

DatePicker(selection: $selectedDate,
           in: Date()...Date().advanced(by: 7*24*3600),
           displayedComponents: [.date, .hourAndMinute]) {
    Text("Date")
}


Source Code:

struct ContentView: View {
    
    private var dateFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        return dateFormatter
    }
    
    @State var selectedDate = Date()
    
    var body: some View {
        VStack {
            DatePicker(selection: $selectedDate,
                       in: Date()...Date().advanced(by: 7*24*3600),
                       displayedComponents: [.date, .hourAndMinute]) {
                Text("Date")
            }
            Text("You have chosen: \(selectedDate, formatter: dateFormatter)")
        }
    }
}

 

Follow me on:

Comentarios


bottom of page