IOS TOPICS

IOS Introduction
Swift UI Label
Swift UI Button
Swift UI Text Field
Swift UI Slider
Swift UI Switch
Swift UI Stepper
Swift UI Date Picker
Swift UI Segmented Control
Views
Table View
Collection Views
SCROLL VIEW
iOS Content View
iOS View Controllers
iOS Bar interface
iOS Navigation interface
iOS Architect Pattern
iOS Libraries
iOS Web request and parsing
iOS user defaults
iOS Coredata and database

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<Date> = { 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

ios output

And up til

ios output

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.

ios output

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:

ios output