The UIDatePicker constraint dates to a specific time. For example, entering DOB in a limited age limit

In my code, I have a UITextField that, when the user logs in, opens the UIDatePicker so that the user can easily and efficiently scroll them to the date of birth. Obviously, we do not want the UIDatePicker to scroll until 2015 and end as it is at present. Since this is a Date of Entry input field, I will also need to limit the entries to 16 years + How can I do it?

class SignUpViewController: UIViewController, UITextFieldDelegate { var datePicker:UIDatePicker! @IBOutlet weak var dateTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // UI DATE PICKER SETUP var customView:UIView = UIView(frame: CGRectMake(0, 100, 320, 160)) customView.backgroundColor = UIColor.clearColor() datePicker = UIDatePicker(frame: CGRectMake(0, 0, 320, 160)) datePicker.datePickerMode = UIDatePickerMode.Date customView.addSubview(datePicker) dateTextField.inputView = customView var doneButton:UIButton = UIButton (frame: CGRectMake(100, 100, 100, 44)) doneButton.setTitle("Done", forState: UIControlState.Normal) doneButton.addTarget(self, action: "datePickerSelected", forControlEvents: UIControlEvents.TouchUpInside) doneButton.backgroundColor = UIColor .grayColor() dateTextField.inputAccessoryView = doneButton 
+12
xcode swift nsdate uidatepicker
source share
2 answers

You can use dateByAddingUnit and subtract 16 years from the current date to set the maximum date for your DatePicker as follows:

 datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -16, toDate: NSDate(), options: []) 

Xcode 10.2.1 • Swift 5

 datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date()) 
+31
source share

UIDatePicker has maximumDate , which you can set. Just set the Date mode to IB and add: datePicker.maximumDate = NSDate(timeIntervalSinceNow: -504911232)

-504911232 means 16 to this day (years of a leap year)

-2
source share

All Articles