I have an NSPopUpButton that, by default, is as wide as necessary to fit the widest text in its menu.
Now I need the control to resize itself depending on the currently chosen (shown) menu item.
For example, if the menu contains
- A
- XXXXXXXXXX
And if the user chooses "A", then the control should be only as wide as necessary to show "A".
How do I accomplish that? (I am using Auto Layout)
I've tried to set the control's content hugging priority to 1000 and its compression resistance to 1, but that has no effect, it seems.
I suspect I need to subclass the control and implement intrinsicContentSize
. But what's the proper way to determine the needed width of the selectedItem
, then?
For instance, the follow code behaves the way I want it, but it relies on impirically obtained values (30 px for the extra width of the pop-up menu's indicators), which isn't safe - e.g, if macOS changes the default font size, this may not fit any more.
- (NSSize) intrinsicContentSize {
NSSize size = super.intrinsicContentSize;
NSPopUpButtonCell *currentCell = self.selectedCell;
CGFloat w = currentCell.titleWidth;
return NSMakeSize (w+30, size.height);
}