限制特定时间的UIDatePicker日期。如输入DOB到限制年龄限制

时间:2015-07-14 22:06:16

标签: xcode swift nsdate uidatepicker

在我的代码中,我有一个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

2 个答案:

答案 0 :(得分:31)

您可以使用dateByAddingUnit并从当前日期减去16年来设置datePicker的最大日期,如下所示:

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

Xcode 8 beta 6•Swift 3

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

答案 1 :(得分:-2)

UIDatePickermaximumDate您可以设置。只需将模式设置为"日期"在IB中添加: datePicker.maximumDate = NSDate(timeIntervalSinceNow: -504911232)

-504911232表示今天之前的16(会计闰年)