@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:
てラベルを変更するだけで、追加のコードなしで「正常に機能」します。