14

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() {
        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
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Martin Q
  • 403
  • 1
  • 6
  • 13

2 Answers2

36

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: [])

Xcode 10.2.1 • Swift 5

datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
-2

UIDatePicker has a maximumDate that you can set. Simply set the mode to "Date" in IB and add: datePicker.maximumDate = NSDate(timeIntervalSinceNow: -504911232)

-504911232 means 16 before today(accounting leap years)

SentientBacon
  • 1,509
  • 3
  • 11
  • 19
  • No it doesn't mean that. 504489600 are 15 years, 11 months and 25 days. Hint: leap years. And that's why you don't do date calculations with seconds. – Matthias Bauch Jul 14 '15 at 22:31
  • Changed it to account for about 4 leap days – SentientBacon Jul 14 '15 at 22:34
  • Besides reinventing NSCalendar you can try whatever you want, you won't be able to fix it. Seconds cannot be used if you want to describe relative timespans that are longer than one hour. With a proper calendar you cannot account for daylight saving, leap years or skipped days (there's at least one country that has recently skipped a whole day). – Matthias Bauch Jul 14 '15 at 22:46