Custom NSView in NSMenuItem not receiving mouse events

落花浮王杯 提交于 2019-12-03 03:22:18

Add this method to your custom NSView and it will work fine with mouse events

- (void)mouseUp:(NSEvent*) event {
    NSMenuItem* mitem = [self enclosingMenuItem];
    NSMenu* m = [mitem menu];
    [m cancelTracking];
    [m performActionForItemAtIndex: [m indexOfItem: mitem]];
}

But i'm having problems with keyhandling, if you solved this problem maybe you can go to my question and help me a little bit.

fabian

Add this to your custom view and you should be fine:

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
    return YES;
}

I added this method to my custom view, and now everything works beautifully:

- (void)viewDidMoveToWindow {
    [[self window] becomeKeyWindow];
}

Hope this helps!

So far, the only way to achieve the goal, is to register a tracking area manually in updateTrackingAreas - that is thankfully called, like this:

override func updateTrackingAreas() {
    let trackingArea = NSTrackingArea(rect: bounds, options: [.enabledDuringMouseDrag, .mouseEnteredAndExited, .activeInActiveApp], owner: self, userInfo: nil)
    addTrackingArea(trackingArea)
}
Shumais Ul Haq

Recently I needed to show a Custom view for a NSStatusItem, show a regular NSMenu when clicking on it and supporting drag and drop operations on the Status icon.

I solved my problem using, mainly, three different sources that can be found in this question.

Hope it helps other people.

See the sample code from Apple named CustomMenus In there you'll find a good example in the ImagePickerMenuItemView class.

It's not simple or trivial to make a view in a menu act like a normal NSMenuItem. There are some real decisions and coding to do.

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