Hide MAAttachedWindow when clicking outside

梦想与她 提交于 2019-12-18 03:46:23

问题


I'm using an MAAttachedWindow to display a custom window under a NSStatusItem in the Menubar. Everything works fine, but I can't find an easy way to hide it when the user clicks outside of the window. I want to implement this behavior because it's what the user expects.

This is the code used to display the MAAttachedWindow:

- (void)toggleAttachedWindowAtPoint:(NSPoint)pt {
    if (!self.attachedWindow) {  
        self.attachedWindow = [[MAAttachedWindow alloc] initWithView:logView
              attachedToPoint:pt 
               inWindow:nil 
                 onSide:MAPositionBottom 
                atDistance:5.0];

  [self.attachedWindow setLevel:kCGMaximumWindowLevel];
 }

 if(isVisible)
  [self.attachedWindow makeKeyAndOrderFront:self];
 else
  [self.attachedWindow orderOut];
}

This code gets triggered by an NSStatusItem with a custom view which intercepts a click on it.


回答1:


You should be able to do this via the window's delegate method:

- (void)windowDidResignKey:(NSNotification *)notification

Set yourself as the window's delegate, and implement that to call through to your toggle method.




回答2:


This is based on Carter Allen answer, but maybe will be helpfull to someone as i lost couple of hours trying to figure out the reason behind an EXEC_BAD_ACCESS, in short you can't release the attachedWindow inside his windowDidResignKey notification, so use autorelease:

- (void)windowDidResignKey:(NSNotification *)aNotification {
    NSLog(@"MainWinDelegate::windowDidResignKey: %@", [aNotification object]);

    if (fAttachedWindow && [aNotification object] == fAttachedWindow) {
        [window removeChildWindow:fAttachedWindow];
        [fAttachedWindow orderOut:self];
        [fAttachedWindow autorelease];
        fAttachedWindow = nil;
    }
}


来源:https://stackoverflow.com/questions/4696689/hide-maattachedwindow-when-clicking-outside

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