Ariel Gemilang Ariel Gemilang - 5 months ago 56
Swift Question

Date Picker, User cannot go back to previous date Swift

I have Date Picker

I already set the current Date, and i want to make User cannot scroll back to previous date? is it allowed?

Answer

This is an example to how to do it in Swift 2.2:

// a global var
var datePicker = UIDatePicker()

 // UIDatePicker settings:
 let currentDate: NSDate = NSDate()
 let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
 calendar.timeZone = NSTimeZone(name: "UTC")!
 let components: NSDateComponents = NSDateComponents()
 components.calendar = calendar
 components.year = -18
 let minDate: NSDate = calendar.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
 components.year = -150
 let maxDate: NSDate = calendar.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
 datePicker.dateOfBirthUIDatePicker.minimumDate = minDate
 datePicker.dateOfBirthUIDatePicker.maximumDate = maxDate