Lion 中的自动布局应该可以非常简单地让文本字段(以及标签)随其包含的文本一起增长。
文本字段在 Interface Builder 中设置为换行。
有什么简单而可靠的方法可以做到这一点?
方法intrinsicContentSize
in NSView
返回视图本身认为的其内在内容大小。
NSTextField
计算此值时不考虑wraps
其单元格的属性,因此如果放置在单行上,它将报告文本的尺寸。
因此,一个自定义子类NSTextField
可以重写此方法以返回更好的值,例如单元格提供的值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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)