Search code examples
objective-ccocoanspopover

NSPopover shows up even if the main window is not active


I'm showing a popover programmatically, like this:

popover = [NSPopover new];    
popover.contentViewController = popoverController;
popover.animates = YES;
popover.delegate = popoverController;
popover.behavior = NSPopoverBehaviorSemitransient;

[popover showRelativeToRect:[textfield bounds] 
                     ofView:textfield 
              preferredEdge:NSMaxYEdge];

where textfield is a NSTextfield under which the popover will show up. It all works but the problem is that the popover will show up even if the window is hidden and not active, like if it is coming from nowhere (the main window remains hidden while the popover shows up). Any help how to solve this?


Solution

  • You need to check if your window is main or key window and just then show popover. Just like this:

    if ([yourWindowOutlet isMainWindow]) {
        // show popover
    }
    

    or

    if ([yourWindowOutlet isKeyWindow]) {
        // show popover
    }