问题
Hi Is it possible to have a NSDatePicker representing a nil object? Something like -/-/- or any other way.
Thanks, Radu
回答1:
Short answer: No
NSDatePicker simply ignores invalid dates and nil.
For example, this does not update the NSDatePicker, the old value remains:
[datePicker setDateValue:nil];
Only solution: Detect nil and do something specific:
if(date == nil) {
// Set Specific Date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *nilDate = [dateFormat dateFromString:@"20000101"];
[datePicker setDateValue:nilDate];
// Or Disable
[datePicker setEnabled:FALSE];
} else {
// Update Date
[datePicker setDateValue:date];
}
回答2:
The following NSDatePicker subclass can show an empty date state and represents a nil binding as such.
https://github.com/ThesaurusSoftware/TFDatePicker
Run the TFDatePickerTest to see how it behaves.
回答3:
You can force NSDatePicker to show no date by setting the NSDatePickerElementFlags to 0:
@IBOutlet weak var datePicker: NSDatePicker!
datePicker.datePickerElements = NSDatePickerElementFlags(rawValue: 0)
However, you must then handle showing a date when the datePicker is selected. Here is a subclass which does this, showing the current date when an empty datePicker is selected:
class MyDatePicker: NSDatePicker {
var date: Date? {
didSet {
if let date = date {
self.dateValue = date
self.datePickerElements = .yearMonthDayDatePickerElementFlag
} else {
self.datePickerElements = NSDatePickerElementFlags(rawValue: 0)
}
}
}
override func becomeFirstResponder() -> Bool {
if date == nil {
date = Date()
}
return true
}
override func resignFirstResponder() -> Bool {
editing = false
date = self.dateValue
return super.resignFirstResponder()
}
}
来源:https://stackoverflow.com/questions/5487479/empty-nsdatepicker