objective-cmacoscocoanspopover

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.


Solution

  • 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.