如何让 NSTextField 随着自动布局中的文本增长? [英] How to let NSTextField grow with the text in auto layout?

查看:32
本文介绍了如何让 NSTextField 随着自动布局中的文本增长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Lion 中的自动布局应该让文本字段(以及标签)随着它所包含的文本增长变得相当简单.

Auto layout in Lion should make it fairly simple to let a text field (and hence a label) grow with text it holds.

文本字段设置为在 Interface Builder 中换行.

The text field is set to wrap in Interface Builder.

有什么简单可靠的方法可以做到这一点?

What is a simple and reliable way to do this?

推荐答案

NSView 中的方法 intrinsicContentSize 返回视图本身认为的其内在内容大小.

The method intrinsicContentSize in NSView returns what the view itself thinks of as its intrinsic content size.

NSTextField 在不考虑其单元格的 wraps 属性的情况下计算此值,因此如果将文本放在一行中,它将报告文本的尺寸.

NSTextField calculates this without considering the wraps property of its cell, so it will report the dimensions of the text if laid out in on a single line.

因此,NSTextField 的自定义子类可以覆盖此方法以返回更好的值,例如单元格的 cellSizeForBounds: 方法提供的值:

Hence, a custom subclass of NSTextField can override this method to return a better value, such as the one provided by the cell's cellSizeForBounds: method:

-(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];
}

这篇关于如何让 NSTextField 随着自动布局中的文本增长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆