NSPopover Not Appearing

2019-07-12 20:21发布

问题:

I really wish I could be more specific, but unfortunately, I cannot. All appropriate objects are non-nil, and all appropriate method calls are going through (presumably) successfully, but my NSPopover just never shows up. None of the delegate methods get called, either.

// ivars
NSPopover *tagPopover;
NSViewController *tagPopoverViewController;

// in method to display popover
tagPopover = [[NSPopover alloc] init];
[tagPopover setBehavior: NSPopoverBehaviorApplicationDefined];
[tagPopover setDelegate: self];
tagPopoverViewController = [[MYViewController alloc] initWithNibName: @"MYViewController" bundle: nil];
[tagPopover setContentViewController: tagPopoverViewController];
[tagPopover setContentSize: tagPopoverViewController.view.frame.size];

[tagPopover showRelativeToRect: NSMakeRect(700, 400, 5, 5) // Screen coordinates
                        ofView: [[NSApp keyWindow] contentView]
                 preferredEdge: NSMinYEdge];

回答1:

Turns out the coordinate system was wrong:

NSRect theRect = [[NSApp keyWindow] convertRectFromScreen: NSMakeRect(700, 400, 5, 5)];
[tagPopover showRelativeToRect: theRect // Window Coordinates
                        ofView: [[NSApp keyWindow] contentView]
                 preferredEdge: NSMinYEdge];

Needed to convert it to the window's coordinate system first.



回答2:

I suspect that tagPopoverViewController.view.frame is NSZeroRect, since frames are set to that before they start to go onscreen (e.g. they are meaningless as they come out of xibs/storyboards). Are you sure you need that line? The documentation mentions that the contentSize is bound to the content-view's size anyway.