prosseek
prosseek

Reputation: 190709

Setting up NSDatePicker delegate

I have a NSDatePicker (NSDatePicker* datePicker), and set its delegate as the main application (self). I programmed as follows.

  1. Make self datePicker delegate

    [[datePicker cell] setDelegate:self];

  2. Set datePickerAction: to be called when control is clicked.

    [datePicker setAction:@selector(datePickerAction:)];

This is the method.

- (IBAction)datePickerAction:(id)sender
{

    if( [[[NSApplication sharedApplication] currentEvent] modifierFlags] & 
       NSShiftKeyMask )
        NSLog(@"shift pressed %@", [datePicker dateValue]);

    else
        NSLog(@"hello %@", [datePicker dateValue]);

}

The problem is that delegation doesn't seem to work when I click the date in the NSDatePicker calendar.

enter image description here

Upvotes: 3

Views: 6042

Answers (4)

Tommy
Tommy

Reputation: 169

You need to subclass NSDatePicker and override MouseDown Event and connect it to delegate. Here is the codes.

CustomDatePick.h

#import <Cocoa/Cocoa.h>

@protocol CustomPickerDelegate

- (void)didPickerClick;

@end

@interface CustomDatePicker : NSDatePicker

@property (assign) id <CustomPickerDelegate> myDelegate;

@end

CustomDatePick.m

#import "CustomDatePicker.h"

@implementation CustomDatePicker

- (void)mouseDown:(NSEvent *)event {
    [super mouseDown:event];

    [self.myDelegate didPickerClick];
}

@end

Upvotes: 0

fredzouille
fredzouille

Reputation: 31

You have to add this method to your code :

- (void)datePickerCell:(NSDatePickerCell *)aDatePickerCell validateProposedDateValue:(NSDate **)proposedDateValue timeInterval:(NSTimeInterval *)proposedTimeInterval
{
   NSString *aDate = [myDateFormat stringFromDate:*proposedDateValue];
}

From IB, select the DatePickerCell, right click, drag the delegate entry to the File's Owner box.

Upvotes: 3

indragie
indragie

Reputation: 18122

Set the delegate of the NSDatePicker itself instead of its cell:

[datePicker setDelegate:self]

Upvotes: -4

Conbobulate
Conbobulate

Reputation: 51

Delegation behaves unexpectedly for NSDatePicker. One might think that becoming the delegate for an NSDatePicker means that you will receive notification events from NSControl, NSDatePicker's parent class.

This isn't the case, though. The delegate is set on the NSDatePicker's cell, so your delegate class will receive events from the cell (conforming to the NSDatePickerCellDelegate protocol), not the control. There's only one of these cell delegate methods, a validation method.

You can jump through hoops subclassing NSDatePicker and getting the delegation to occur on the control, but then you lose the validation delegation, which other parts of the view hierarchy seem to depend on. I suspect the target/action method, or using bindings, is the only way to intercept user interaction in this case.

Upvotes: 2

Related Questions