Resizing nspopover

2019-06-07 00:16发布

问题:

I am trying to resize an NSPopover prior to displaying it by setting the frame of the NSView it contains using the method:

setFrameSize:

However, when I try to display the popover by calling:

showRelativeToRect: ofView: preferredEdge:

The view returns to its previous size. Why is this happening? Is there another way I should be sizing the popover?

Thanks in advance, Ben.

回答1:

There's a setContentSize on the popover, but I have the impression this doesn't work so well. I mean it works, but resizes the content (including child views). So the better way is to create a new NSViewController and assign it the new view. On setting this new controller on the NSPopover the size is properly respected and if the popover is currently shown it will animate to the new view.

If you can't do this but instead want to resize the content in place use something like this:

NSRect frame = valuePopupList.frame;
frame.origin = NSMakePoint(2, 2);

... determine new frame ...

NSSize contentSize = frame.size;
contentSize.width += 4; // Border left/right.
contentSize.height += 4; // Ditto for top/bottom.
if (contentSize.height < 26) {
    contentSize.height = 26;
}
valuePopupList.frame = frame;
statementsPopover.contentSize = contentSize;

[statementsPopover showRelativeToRect: area ofView: view preferredEdge: NSMaxXEdge];
valuePopupList.frameOrigin = frame.origin;


回答2:

You should implement -preferredContentSize in your NSViewController that is contained by the popover. That seems to be the most reliable way of controlling the popover size.