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

时间:2011-08-27 04:30:38

标签: xcode cocoa macos interface-builder nsbutton

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

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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:8)

当然!只需使用Auto Layout! :)