3

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

  • Q : What's wrong with this delegation? The target/action method works fine.
  • Q : What document can I use for what delegation method is supported for NSDatePicker?
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

4 Answers4

3

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.

2

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.

0

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
Tommy
  • 159
  • 3
  • 19
-4

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

[datePicker setDelegate:self]

Charan
  • 4,940
  • 3
  • 26
  • 43
indragie
  • 18,002
  • 16
  • 95
  • 164