SwiftUI DatePicker -- Allow no date at all?

Viewed 673

I'm working on my first SwiftUI app, and have implemented a Form with one of the fields being a DatePicker. However, this value is completely optional. So, it is possible that the user doesn't enter a value at all. I'm unable to figure out, though, how I can make it so that the user doesn't need to enter the value. The code itself is rather simple:

    DatePicker(selection: $expirationDate,
               displayedComponents: .date) {
        Text("Expiration")
    }

Is there a way so that I can indicate that $expirationDate can have a Date or can be nil? The DatePicker by default seems to set the value to the current Date and I couldn't figure out a way to override that behavior. Thoughts?

1 Answers

You can add Text on top of the DatePicker that does not receive touch events, then add a white background with a prompt. This will allow the date to still be clickable.

struct DatePickerNullable: View {
    
    let label:String
    @Binding var date:Date?
    @State private var hidenDate:Date = Date()
    
    init(_ label:String, selection:Binding<Date?>){
        self.label = label
        self._date = selection
    }
    
    
    var body: some View {
        GeometryReader{ proxy in
            ZStack{
                DatePicker(label, selection: $hidenDate, displayedComponents: .date)
                if date == nil{
                    Text(label)
                        .italic()
                        .foregroundColor(.gray)
                        .frame(width: proxy.size.width - CGFloat(label.count * 8), alignment: .trailing)
                        .background(Color.white)
                        .frame(maxWidth: .infinity, alignment: .trailing)
                        .allowsHitTesting(false)
                }
            }.onChange(of: hidenDate, perform: { _ in
                self.date = hidenDate
            })
        }
    }
}

Default state

Clicked state

Related