39

Lion の自動レイアウトにより、テキスト フィールド (したがってラベル) を保持するテキストとともに拡張することがかなり簡単になります。

テキスト フィールドは、Interface Builder で折り返すように設定されています。

これを行うための簡単で信頼できる方法は何ですか?

4

3 に答える 3

52

のメソッドは、ビュー自体がその固有のコンテンツサイズと見なすものintrinsicContentSizeを返します。NSView

NSTextFieldセルのプロパティを考慮せずにこれを計算するwrapsため、1行に配置されている場合は、テキストの寸法が報告されます。

したがって、のカスタムサブクラスは、このメソッドをオーバーライドして、セルのメソッドNSTextFieldによって提供される値など、より適切な値を返すことができます。cellSizeForBounds:

-(NSSize)intrinsicContentSize
{
    if ( ![self.cell wraps] ) {
        return [super intrinsicContentSize];
    }

    NSRect frame = [self frame];

    CGFloat width = frame.size.width;

    // Make the frame very high, while keeping the width
    frame.size.height = CGFLOAT_MAX;

    // Calculate new height within the frame
    // with practically infinite height.
    CGFloat height = [self.cell cellSizeForBounds: frame].height;

    return NSMakeSize(width, height);
}

// you need to invalidate the layout on text change, else it wouldn't grow by changing the text
- (void)textDidChange:(NSNotification *)notification
{
    [super textDidChange:notification];
    [self invalidateIntrinsicContentSize];
}
于 2012-05-05T16:28:20.120 に答える