简体   繁体   中英

Resize NSPopupButton to its selected title

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM