gpt4 book ai didi

ios - UIDatePicker 最小日期和最大日期

转载 作者:行者123 更新时间:2023-11-30 13:42:06 30 4
gpt4 key购买 nike

我尝试设置最小和最大日期来限制用户的选择,但它不起作用:

    override func viewDidLoad() {
let datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
tfDateNaissance.inputView = datePickerView

let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let currentDate: NSDate = NSDate()
let components: NSDateComponents = NSDateComponents()

components.year = -18
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

components.year = -150
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

datePickerView.minimumDate = minDate
datePickerView.maximumDate = maxDate


datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)

let pickerToolBar = UIToolbar()
pickerToolBar.barStyle = UIBarStyle.Black //you can change the style
pickerToolBar.translucent = true
pickerToolBar.tintColor = UIColor.whiteColor() // or other colours
pickerToolBar.sizeToFit()

let spaceButtonPicker = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButtonPicker = UIBarButtonItem(title: "Ok", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelDatePicker:")
pickerToolBar.setItems([cancelButtonPicker, spaceButtonPicker], animated: false)
pickerToolBar.userInteractionEnabled = true
tfDateNaissance.inputAccessoryView = pickerToolBar
}


func datePickerValueChanged(sender: UIDatePicker) {
let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "dd/MM/yyyy"

// dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
//
// dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle

tfDateNaissance.text = dateFormatter.stringFromDate(sender.date)

}

func cancelDatePicker(sender: UIBarButtonItem){
if tfProjet.isFirstResponder(){
tfProjet.resignFirstResponder()
} else if tfDateNaissance.isFirstResponder(){
tfDateNaissance.resignFirstResponder()
}
}

我在堆栈溢出上找到了这段代码,我没有收到任何错误,但我可以选择 2200 作为年份。我认为这是因为它是一个输入 View ,那么如何呢?

最佳答案

minDate 晚于 maxDate:

    components.year = -150
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

components.year = -18
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

datePickerView.minimumDate = minDate
datePickerView.maximumDate = maxDate

关于ios - UIDatePicker 最小日期和最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35435317/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com