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

Rya*_*yan 13 macos xcode cocoa interface-builder nsbutton

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

我希望按钮能够自动调整大小(具有固定的右侧位置 - 因此它向左延伸)以适合以编程方式插入的任何长度的字符串作为按钮文本.但我无法弄明白.有什么建议?提前致谢!

Rob*_*ger 15

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

你不能自动执行此操作,但在子类中很容易做到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
Run Code Online (Sandbox Code Playgroud)

这样您就可以RKSizeToFitButton在Interface Builder中设置按钮的类,然后调用setStringValue:按钮来更改其标签将"正常工作"而无需其他代码.

  • 当然,但我期待子类被称为"RKSizeToFitButton"之类的东西,你根本不需要改变你的代码,因为它是`NSButton`的直接替代品.毕竟,OP想要一种自动方法来做到这一点. (3认同)
  • 该方法更合适的名称是`setStringValueAndSizeToFit:`. (2认同)

jtb*_*des 8

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