Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPopover - Hide when focus lost? (clicked outside of popover)

I'm using the doubleClickAction of a NSTableView to display a NSPopover. Something like this:

NSInteger selectedRow = [dataTableView clickedRow];
NSInteger selectedColumn = [dataTableView clickedColumn];


// If something was not selected, then we cannot display anything.
if(selectedRow < 0 || selectedColumn < 0)
{
    NSLog(@"Invalid selected (%ld,%ld)", selectedRow, selectedColumn);
    return;
} // End of something was not selected

// Setup our view controller, make sure if there was already a popover displayed, that we kill that one off first. Finally create and display our new popover.
DataInspectorViewController * controller =
[[DataInspectorViewController alloc] initWithNibName: @"DataInspectorViewController"
                                              bundle: nil];

if(nil != dataPreviewPopover)
{
    [dataPreviewPopover close];
} // End of popover was already visible

dataPreviewPopover = [[NSPopover alloc] init];
[dataPreviewPopover setContentSize:NSMakeSize(400.0f, 400.0f)];
[dataPreviewPopover setContentViewController:controller];
[dataPreviewPopover setAnimates:YES];
[dataPreviewPopover showRelativeToRect: [dataTableView frameOfCellAtColumn: selectedColumn row: selectedRow]
                     ofView: dataTableView
              preferredEdge: NSMinYEdge];

Which works just fine. My popovers get created and removed on the cells that I double click on . The problem is, I want to the popover to go away if I click anywhere outside of it (like a single click on another cell). I have been looking around, but for the life of me cannot figure out how to do it.

This is something I would assume is built into a popover, (I'm fairly certain it was in the iOS UIPopoverController class) so I'm just wondering if im missing something simple.

like image 534
Kyle Avatar asked Feb 16 '13 12:02

Kyle


2 Answers

You need to change the property behavior of your popover (in code or on interface builder) to:

popover.behavior = NSPopover.Behavior.transient;

NSPopover.Behavior.transient
The system will close the popover when the user interacts with a user interface element outside the popover.

Read more about this in Apple's documentation.

like image 121
sergeyne Avatar answered Oct 20 '22 08:10

sergeyne


the .transient flag doesn't work for me.

However I can make things work by the following:

1) Whenever I show my popover I make sure I activate the app (my app is a menu-bar app, so this doesn't happen automatically)

NSApp.activate(ignoringOtherApps: true)

2) When I click outside the app, then my app will be deactivated. I can detect this in the AppDelegate

func applicationWillResignActive(_ notification: Notification) {
    print("resign active")
}

and act accordingly

like image 14
Confused Vorlon Avatar answered Oct 20 '22 07:10

Confused Vorlon