将NSPopupButton调整为其选定的标题

daf*_*afi 2 cocoa nspopupbuttoncell nspopupbutton

我有一个NSPopupButton,我想要它调整自己以适应所选的标题.

[NSPopupButton sizeToFit]不符合我的需要,因为弹出窗口被调整为最大的标题项而不是当前选定的标题项

我试图在没有成功的情况下尽可能地接近

#define ARROW_WIDTH 20
NSDictionary *displayAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[popup font], NSFontAttributeName, nil];
NSSize titleSize = [popup.titleOfSelectedItem sizeWithAttributes:displayAttributes] + ARROW_WIDTH;
Run Code Online (Sandbox Code Playgroud)

但是常量值ARROW_WIDTH是一个非常脏且容易出错的解决方案.

状态栏上的TextWrangler编码组合就像我需要的那样工作

Dav*_*yle 5

我用文本字段处理这些问题的方法是尝试使用您从未添加到视图层次结构的文本字段来调整大小.您可以在无意重用的对象上调用sizeToFit,然后使用它来确定实际控制需要多宽以适合您需要执行的操作.

因此,在伪代码中,你会这样做(假设你使用ARC,YMMV用于非ARC项目,因为这会泄漏):

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;
Run Code Online (Sandbox Code Playgroud)