添加比例宽度约束(OSX AutoLayout)时如何防止超级视图增长

时间:2018-09-02 09:18:14

标签: macos cocoa autolayout

我有一个测试视图,该视图的内部带有标签(NSTextField),并以编程方式添加了比例宽度约束,以便我的测试视图采用其父视图(主视图控制器的视图)的1/3宽度。当我设置简短标题(例如,标签的“短文本”)时,可以正确显示我的测试视图(它占Superview宽度的1/3)。但是,当我尝试设置长标题(例如,标签的“ long long long long long long long text”)时,将扩大超级视图,并且标签显示全文。我期望不要更改超级视图的大小,测试视图的宽度应为1/3,标签的尾部应截断以显示“ ...”。

测试视图正确显示为短文本: superview is not grown

测试视图显示不正确,带有长文本: superview is grown

我的代码以编程方式为测试视图添加了约束:

TestView *testView = [[TestView alloc] initWithFrame:NSMakeRect(5, 10, 120, 30)];

NSString *title = @"long long long long long long text";
//NSString *title = @"short text";

[testView setTitle:title];

[self.view addSubview:testView];

float multiplierWidth = (float) 1/3;
float multiplierLeading = (float) 1/3;

NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:testView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:testView.superview attribute:NSLayoutAttributeWidth multiplier:multiplierWidth constant:0.0];

NSLayoutConstraint *leadingConstraint = [NSLayoutConstraint constraintWithItem:testView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:testView.superview attribute:multiplierLeading==0?NSLayoutAttributeLeading:NSLayoutAttributeTrailing multiplier:multiplierLeading==0?1.0:multiplierLeading constant:0.0];

NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:testView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:testView.superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:testView.frame.origin.y];

NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:testView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:testView.frame.size.height];

[testView setTranslatesAutoresizingMaskIntoConstraints:NO];

[testView addConstraint:heightConstraint];
[testView.superview addConstraint:topConstraint];

[testView.superview addConstraint:leadingConstraint];
[testView.superview addConstraint:widthConstraint];

这是示例项目:sample project

0 个答案:

没有答案