【发布时间】:2017-06-16 08:38:07
【问题描述】:
我有多行 NSTexField,用于显示静态文本,在每次显示窗口时可能具有不同的长度。这个 NSTextField 有一个高度约束,将其限制为两行。
我想设置行为,NSTextField 只会水平增长这么多,它会填满这两条水平线。 现在,当我将水平压缩阻力设置得更高时,文本字段宽度会增长很多,以在一行上显示所有文本。这是否可能仅通过使用自动布局约束来实现,还是我必须以某种方式计算 nstextfield 宽度?
我尝试在 superview 中重载“布局”方法。但它没有像我预期的那样工作。
- (void)layout
{
[self solveLayoutForView:self];
}
- (void)solveLayoutForView:(NSView*)view
{
for (NSView* subView in [view subviews])
{
if (subView.subviews.count)
[self solveLayoutForView:subView];
else
{
NSLayoutConstraint* height = [subView constraintForAttribute:NSLayoutAttributeHeight];
if (height && height.constant > 17 && [subView isKindOfClass:[NSTextField class]]) // seems like multiline nstextfield
{
NSTextField* textField = (NSTextField*)subView;
textField.preferredMaxLayoutWidth = 0;
[super layout];
textField.preferredMaxLayoutWidth = NSWidth([textField alignmentRectForFrame:textField.frame]);
[super layout];
}
}
}
}
【问题讨论】:
标签: cocoa autolayout width nstextfield