自动调整 NSButton 的大小以适应以编程方式更改的文本 (Xcode)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7212553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:49:11  来源:igfitidea点击:

Automatically resize an NSButton to fit programmatically changed text (Xcode)

xcodecocoamacosinterface-buildernsbutton

提问by Ryan

I have an NSButton (Push Button) with some temporary title text built in Interface Builder / Xcode. Elsewhere, the title text inside the button is changed programmatically to a string of unknown length (actually, many times to many different lengths).

我有一个 NSButton(按钮),里面有一些内置在 Interface Builder/Xcode 中的临时标题文本。在其他地方,按钮内的标题文本以编程方式更改为未知长度的字符串(实际上,多次更改为许多不同的长度)。

I'd like the button to automatically be resized (with a fixed right position--so it grows out to the left) to fit whatever length of string is programmatically inserted as button text. But I can't figure it out. Any suggestions? Thanks in advance!

我希望按钮自动调整大小(具有固定的右侧位置 - 因此它向左长出)以适合以编程方式作为按钮文本插入的任何字符串长度。但我想不通。有什么建议?提前致谢!

回答by Rob Keniger

If you can't use Auto Layout as suggested by @jtbandes (it's only available in Lion), then you can call [button sizeToFit]after setting its string value, which will make the button resize to fit its string. You would then need to adjust its frame based on the new width.

如果您不能按照@jtbandes 的建议使用自动布局(它仅在 Lion 中可用),那么您可以[button sizeToFit]在设置其字符串值后调用,这将使按钮调整大小以适应其字符串。然后您需要根据新宽度调整其框架。

You can't do this automatically, but it would be easy to do in a subclass of NSButton.

您不能自动执行此操作,但在NSButton.

@implementation RKSizeToFitButton
- (void)setStringValue:(NSString*)aString
{
    //get the current frame
    NSRect frame = [self frame];

    //button label
    [super setStringValue:aString];

    //resize to fit the new string
    [self sizeToFit];

    //calculate the difference between the two frame widths
    NSSize newSize = self.frame.size;
    CGFloat widthDelta = newSize.width - NSWidth(frame);
    //set the frame origin
    [self setFrameOrigin:NSMakePoint(NSMinX(self.frame) - widthDelta, NSMinY(self.frame))];
}
@end

This way you can just set your button's class to RKSizeToFitButtonin Interface Builder and then calling setStringValue:on the button to change its label will "just work" with no additional code.

通过这种方式,您可以RKSizeToFitButton在 Interface Builder中将按钮的类设置为,然后调用setStringValue:按钮更改其标签将“正常工作”,无需额外代码。

回答by jtbandes

Sure! Just use Auto Layout! :)

当然!只需使用自动布局!:)