You can use the .maximumDate()
modifier of the DatePicker
to set the maximum selectable date to the current date and time. This will prevent the user from selecting a date or time in the future.
Here's an example:
struct ContentView: View {
@State private var selectedDate = Date()
var body: some View {
VStack {
Text("Select a date and time:")
DatePicker(
"",
selection: $selectedDate,
displayedComponents: [.date, .hourAndMinute]
)
.labelsHidden()
.maximumDate(Date())
}
}
}
In the example above, we're using the .maximumDate(Date())
modifier to set the maximum selectable date to the current date and time. You can customize the format of the displayed date and time components using the displayedComponents
parameter.
Asked: 2022-10-09 11:00:00 +0000
Seen: 14 times
Last updated: Feb 16 '23