我面临着自动布局的奇怪行为。我想向视图控制器添加一个容器视图,然后添加两个标签:一个是左对齐到容器的左侧,另一个是右对齐到容器的右侧。左侧标签布局正确,但右侧标签没有。我刚刚发现添加 20 个点,右标签与父级的左边缘右对齐,而不是右对齐!为什么?我究竟做错了什么?
{
NSArray *cons = nil;
NSLayoutConstraint *cc = nil;
UIView *container = [[UIView alloc]init];
[container setTranslatesAutoresizingMaskIntoConstraints:NO];
[container setBackgroundColor:[UIColor yellowColor]];
[self.view addSubview:container];
cons = [NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[view]-0-|"
options: 0
metrics:nil
views:@{@"view" : container}];
for (NSLayoutConstraint *con in cons)
[self.view addConstraint:con];
cons = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[view]-0-|"
options: 0
metrics:nil
views:@{@"view" : container}];
for (NSLayoutConstraint *con in cons)
[self.view addConstraint:con];
UILabel *currentLabel = [[UILabel alloc]init];
[currentLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[currentLabel setText:@"Punti attuali"];
[currentLabel setBackgroundColor:[UIColor grayColor]];
[container addSubview:currentLabel];
cc = [NSLayoutConstraint constraintWithItem:currentLabel
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:container
attribute:NSLayoutAttributeLeft
multiplier:1.f constant:0.f];
[container addConstraint:cc];
cc = [NSLayoutConstraint constraintWithItem:currentLabel
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:container
attribute:NSLayoutAttributeTop
multiplier:1.f constant:0.f];
[container addConstraint:cc];
UILabel *currentPoint = [[UILabel alloc]init];
[currentPoint setTranslatesAutoresizingMaskIntoConstraints:NO];
[currentPoint setText:@"100"];
[currentPoint setBackgroundColor:[UIColor greenColor]];
[container addSubview:currentPoint];
cc = [NSLayoutConstraint constraintWithItem:currentPoint
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:container
attribute:NSLayoutAttributeRight
multiplier:0.f constant:20.f];
[container addConstraint:cc];
cc = [NSLayoutConstraint constraintWithItem:currentPoint
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:container
attribute:NSLayoutAttributeTop
multiplier:1.f constant:0.f];
[container addConstraint:cc];
}
这应该是一项非常容易完成的任务,但我花了几个小时却找不到解决方案。