I've a NSPopupButton and I want it so resize itself to fit the selected title.

[NSPopupButton sizeToFit] doesn't fit my needs because the popup is resized to the largest title item not to the current selected one

I've tried in may ways without success the closer is

#define ARROW_WIDTH 20
NSDictionary *displayAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[popup font], NSFontAttributeName, nil];
NSSize titleSize = [popup.titleOfSelectedItem sizeWithAttributes:displayAttributes] + ARROW_WIDTH;

But the constant value ARROW_WIDTH is a really dirty and error prone solution.

TextWrangler encoding combo on status bar works like I need

有帮助吗?

解决方案

The way I've handled these problems with text fields is to try the resizing with a text field that you never add to the view hierarchy. You call sizeToFit on an object that you have no intention of reusing, then use that to figure out how wide your actual control needs to be to fit what you need to do.

So, in pseudo code, you'd do this (assuming you're using ARC, YMMV for non-ARC projects as this will leak):

NSArray *popupTitle = [NSArray arrayWithObject: title];
NSPopUpButton *invisiblePopup = [[NSPopUpButton alloc] initWithFrame: CGRectZero pullsDown: YES];
// Note that you may have to set the pullsDown bool to whatever it is with your actual popup button.
[invisiblePopup addItemWithTitle: @"selected title here"];
[invisiblePopup sizeToFit];
CGRect requiredFrame = [invisiblePopup frame];
self.actualPopup.frame = requiredFrame;

其他提示

For projects with autolayout override method intrinsicContentSize in subclass of NSPopUpButton

class NNPopUpButton: NSPopUpButton {
    override var intrinsicContentSize: NSSize {
        let fakePopUpButton = NSPopUpButton(frame: NSZeroRect, pullsDown: false)
        fakePopUpButton.addItem(withTitle: title)
        fakePopUpButton.sizeToFit()
        var requiredFrame = fakePopUpButton.frame
        requiredFrame.size.width -= 35 // reserved space for key equivalent
        return requiredFrame.size
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top