Radu Paise
Radu Paise

Reputation: 285

empty NSDatePicker

Hi Is it possible to have a NSDatePicker representing a nil object? Something like -/-/- or any other way.

Thanks, Radu

Upvotes: 3

Views: 1852

Answers (3)

jbaraga
jbaraga

Reputation: 656

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()
    }
}

Upvotes: 0

Jonathan Mitchell
Jonathan Mitchell

Reputation: 1367

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.

Upvotes: 1

Anne
Anne

Reputation: 27073

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];

}

Upvotes: 5

Related Questions