您可以使用dateByAddingUnit并从当前日期减去16年来设置datePicker的最大日期,如下所示:
datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -16, toDate: NSDate(), options: [])
datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: -16, to: Date())解决方法
在我的代码中,我有一个UITextField,当用户点击时会打开一个UIDatePicker,以使用户能够轻松,高效地滚动至其出生日期。显然,我们不希望UIDatePicker像当前一样向上滚动到2015年。由于这是“出生日期”输入字段,因此我还需要能够将输入限制为16岁以上。我该怎么做呢?
class SignUpViewController: UIViewController,UITextFieldDelegate { var datePicker:UIDatePicker! @IBOutlet weak var dateTextField: UITextField! override func viewDidLoad() {super.viewDidLoad()// UI DATE PICKER SETUPvar customView:UIView = UIView(frame: CGRectMake(0,100,320,160))customView.backgroundColor = UIColor.clearColor()datePicker = UIDatePicker(frame: CGRectMake(0,160))datePicker.datePickerMode = UIDatePickerMode.DatecustomView.addSubview(datePicker)dateTextField.inputView = customViewvar doneButton:UIButton = UIButton (frame: CGRectMake(100,44))doneButton.setTitle('Done',forState: UIControlState.Normal)doneButton.addTarget(self,action: 'datePickerSelected',forControlEvents: UIControlEvents.TouchUpInside)doneButton.backgroundColor = UIColor .grayColor()dateTextField.inputAccessoryView = doneButton