Adding Ranges To Restrict Input
Adding ranges to restrict input:
We can restrict either both upper and lower bounds which is a closed range or restrict either one with a partial range.
Example of a closed range that allows picking any date in the years 2000 to 2020:
Code:
struct ContentView: View {
@State private var date = Date()
let dateRange: ClosedRange = {
let calendar = Calendar.current
let startComponents = DateComponents(year: 2000, month: 1, day: 1)
let endComponents = DateComponents(year: 2020, month: 12, day: 31, hour: 23, minute: 59, second: 59)
return calendar.date(from:startComponents)!
...
calendar.date(from:endComponents)!
}()
var body: some View {
DatePicker(
"Start Date",
selection: $date,
in: dateRange,
displayedComponents: [.date, .hourAndMinute]
)
}}
Output:
On running this code we can see that we can only select dates from January 2020
And up til
Values selected out of this range automatically get corrected to these limiting values.
For Partial selections:
To create a date picker that only selects dat from Today onwards we can use:
Code:
struct ContentView: View {
@State var birthday = Date()
var body: some View {
VStack {
DatePicker("Enter your birthday", selection: $birthday, in: Date()...)
Text("Your birthday is on: \(birthday)")
}.padding()
}
}
Output:
As shown below, you can only select date and time from the date and time forward from that day.
To limit partially Till today use:
Code:
struct ContentView: View {
@State var birthday = Date()
var body: some View {
VStack {
DatePicker("Enter your birthday", selection: $birthday, in: ...Date())
Text("Your birthday is on: \(birthday)")
}.padding()
}
}
Output: