History
Loading...
Loading...
September 15, 2025
in: parameter with DatePicker to restrict date selection ranges. For booking apps, use DatePicker("Check-in", selection: $checkIn, in: Date()...Date().addingTimeInterval(365*24*3600)) to prevent past dates and limit future bookings to one year.This wrapper combines range validation with user feedback, providing immediate visual constraints through the DatePicker's `in:` parameter while adding graceful error handling for edge cases where invalid dates might still be set programmatically.
struct ValidatedDatePicker<Label: View>: View {
let selection: Binding<Date>
let range: ClosedRange<Date>?
let displayedComponents: DatePicker.Components
let label: () -> Label
@State private var showingInvalidDateAlert = false
var body: some View {
DatePicker(selection: Binding(
get: { selection.wrappedValue },
set: { newDate in
if let range = range, range.contains(newDate) {
selection.wrappedValue = newDate
} else {
showingInvalidDateAlert = true
}
}
), displayedComponents: displayedComponents) {
label()
}
.alert("Invalid Date", isPresented: $showingInvalidDateAlert) {
Button("OK") { }
} message: {
Text("Please select a date within the allowed range.")
}
}
}Native DatePicker constraints can sometimes be bypassed through programmatic changes or accessibility tools. This pattern ensures data integrity while maintaining excellent user experience through clear feedback and prevention of invalid states in your app's data flow.