Search code examples
cocoainterface-buildernsdatepicker

Can NSDatePicker have a contextual menu?


Ive been adding contextual menus to an OSX app I'm developing, and have successfully created a menu for a table view. However I'm having problems adding a contextual menu to a NSDatePicker. I've connected the 'menu' outlet to a NSMenu, but right clicking on the NSDatePicker doesn't bring up the menu.

I've checked the menu property on the date picker and it appears to be set correctly.

Is there an inherent issue with trying to create a contextual menu for a NSDatePicker? If so is there a way to get this working (short of reimplementing NSDatePicker)? I'd also prefer to avoid having an extra button to display the menu if at all possible - right clicking on the date picker is the obviously intuitive way this should work.


Solution

  • On OS X 10.9.5, class-dump shows that NSDatePicker overrides -rightMouseDown: (as well as -rightMouseDragged: and -rightMouseUp:). I'm guessing it doesn't call through to super and so is (accidentally?) blocking the contextual menu.

    First, does right-dragging in a date picker do something unique? I've not been able to see it, but who knows. It may depend on the datePickerStyle and/or datePickerMode.

    Also, I don't see an override of -mouseDown:. So, I bet that Control-clicking would bring up the contextual menu.

    I recommend that you accept this limitation. However, if you really want to force the issue, you'll probably need to subclass NSDatePicker and override the -rightMouse... methods. For -rightMouseDown:, you could call NSMenu* menu = [self menuForEvent:theEvent] and, if that returns a menu, call [NSMenu popUpContextMenu:menu withEvent:theEvent forView:self]. Otherwise, do nothing (i.e. don't call through to super).

    For the other two methods, you should probably just do nothing to prevent the superclass methods from getting confused by seeing right-drag and right-mouse-up events when it didn't get the right-mouse-down event.