我正在向 a 添加一个 UIViewUIScrollView
并对其进行约束,使其填充水平空间,除了一些边距。我的视觉约束如下所示:
@"|-16-[theLineView]-16-|"
我已将视图设置为一个像素高,因此它将显示为一条线,并将其放置在两个文本标签之间:
@"V:[someOtherStuff]-[aTextLabel]-[theLineView]-[anotherLabel]"
但是,我发现线条的宽度只会扩大到其上方/下方最长标签的宽度。
为什么会这样?
PS我读过这个http://developer.apple.com/library/ios/#technotes/tn2154/_index.html
代码
以下是在 iPad sim 上展示此问题的测试项目中的完整视图控制器代码。
- (void)viewDidLoad
{ [超级 viewDidLoad];
self.scrollView = [[UIScrollView alloc] init];
self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
self.scrollView.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.scrollView];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[scrollView]|"
options:0
metrics:0
views:@{@"scrollView":self.scrollView}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|"
options:0
metrics:0
views:@{@"scrollView":self.scrollView}]];
self.line1 = [[UIView alloc] init];
self.line2 = [[UIView alloc] init];
self.label1 = [[UILabel alloc] init];
self.label2 = [[UILabel alloc] init];
self.label3 = [[UILabel alloc] init];
for (UILabel *label in @[self.label1, self.label2, self.label3])
{
label.text = @"I am a label and I am long enough that I can be multiline on an iphone but single on ipad";
}
for (UIView *view in @[self.line1, self.line2, self.label1, self.label2, self.label3])
{
view.translatesAutoresizingMaskIntoConstraints = NO;
view.backgroundColor = [UIColor redColor];
[self.scrollView addSubview:view];
}
//horizontal layout - all views/labels should fill the horizontal space expect for margin
for (UIView *view in @[self.line1, self.line2, self.label1, self.label2, self.label3])
{
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-16-[view]-16-|"
options:0
metrics:0
views:@{@"view":view}];
[self.scrollView addConstraints:constraints];
}
//vertical layout - stack em up
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[lab1]-[line1(==1)]-[lab2]-[line2(==1)]-[lab3]-|"
options:0
metrics:0
views:@{@"lab1":self.label1, @"line1":self.line1, @"lab2":self.label2, @"line2":self.line2, @"lab3":self.label3}]];
}