在我的代码中,我有一个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 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
您可以使用dateByAddingUnit并从当前日期减去16年来设置datePicker的最大日期,如下所示:
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())