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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31418218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:28:33  来源:igfitidea点击:

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

xcodeswiftnsdateuidatepicker

提问by Martin Q

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?

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

回答by Leo Dabus

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

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

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

Xcode 10.2.1 ? Swift 5

Xcode 10.2.1 ? 斯威夫特 5

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

回答by SentientBacon

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

UIDatePicker有一个maximumDate你可以设置。只需在 IB 中将模式设置为“日期”并添加: datePicker.maximumDate = NSDate(timeIntervalSinceNow: -504911232)

-504911232 means 16 before today(accounting leap years)

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