empty NSDatePicker

大城市里の小女人 提交于 2019-12-23 15:50:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!