Martin Q Martin Q - 1 year ago 87
Swift Question

Limiting UIDatePicker dates from a particular time. Such as Input DOB to a restricted age limit

In my code, I have a UITextField that when the user taps on opens a UIDatePicker to enable the user to easily and efficiently scroll through to their Date Of Birth. Obviously, we wouldn't want the UIDatePicker to scroll up to 2015 and over as it currently does. As it's a Date Of Birth entry field, i would also need to be able to limit entries to 16years+. How do i do this?

class SignUpViewController: UIViewController, UITextFieldDelegate {

var datePicker:UIDatePicker!

@IBOutlet weak var dateTextField: UITextField!

override func viewDidLoad() {


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

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

Answer Source

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

datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -16, toDate: NSDate(), options: [])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download