0
我正在嘗試設置最小和最大日期限制用戶的選擇,但它不工作:的UIDatePicker minimumDate和maximumDate
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年爲例。我認爲這是因爲它是一個輸入視圖,所以如何去做?
嘗試將其設置爲inputView –
你是否檢查'minDate'和'maxDate'前值設定的最大值和最小值?他們是那個想要的人嗎? – Larme
@LeoDabus不工作 – Ben