Search code examples
iosswiftswiftuicalendarswiftui-list

How can I collapse/expand a datePicker() from compact to graphical, like the calendar app?


I've been trying to achieve the calendar select date UI however the default datePicker() is just a line with some sort of bubble that shows up to select a date and disappears once selected. this is what it looks like, I've been looking for answers all over stack overflow I found one very similar one, however the answers are too complicated with code that I don't honestly understand.

this is my code snippet which is embedded in a list:

 Section(header: CustomText("Schedule Time")){
                            DatePicker("Select Date", selection: $wakeUp, in: Date()...)
                                .background(.white)
                                .cornerRadius(10)
                                .accentColor(.purple)

this is what I want if there's anyone who knows a simplified way of achieving this interface please share, thank you.


Solution

  • What you're seeing is the default behaviour of a system date picker that displays a floating component on activation. On calendar app it's more of an inline style expanding date picker. To achieve this you will need to make use of a state variable and show a date picker as a graphical component on activation. Check the example below.

    struct ContentView: View {
        @State var date: Date = Date()
        @State var showDatePicker = false
        
        var body: some View {
            VStack {
                Button("Date -> format your selected date as desired") {
                    showDatePicker.toggle()
                }
                
                if showDatePicker {
                    DatePicker("Date", selection: $date, displayedComponents: .date)
                        .datePickerStyle(.graphical)
                }
                
                Spacer()
            }
            .padding()
        }
    }