我有一个带有两个子视图的简单视图(控制器):
- (void)viewDidLoad {
[super viewDidLoad];
UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
viewA.translatesAutoresizingMaskIntoConstraints = NO;
viewA.backgroundColor = [UIColor redColor];
[self.view addSubview:viewA];
UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
viewB.translatesAutoresizingMaskIntoConstraints = NO;
viewB.backgroundColor = [UIColor grayColor];
[self.view addSubview:viewB];
}
当然,它们在这一点上是重叠的(我只能看到viewB)。因此,我添加了一个约束以使viewB低于viewA,如下所示:
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:viewB
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:viewA
attribute:NSLayoutAttributeBottom
multiplier:1.f
constant:0]];
这使两个视图都消失了。我究竟做错了什么?
谢谢!
使用约束时,应该对约束进行所有操作(不设置框架),因此仅添加一个约束不足以定义位置和尺寸。我不确定为什么添加一个约束会否定您为视图设置的大小,但似乎确实如此。您应该执行以下操作来充分描述视图,
- (void)viewDidLoad {
[super viewDidLoad];
UIView *viewA = [UIView new];
viewA.translatesAutoresizingMaskIntoConstraints = NO;
viewA.backgroundColor = [UIColor redColor];
[self.view addSubview:viewA];
UIView *viewB = [UIView new];
viewB.translatesAutoresizingMaskIntoConstraints = NO;
viewB.backgroundColor = [UIColor grayColor];
[self.view addSubview:viewB];
NSDictionary *dict = NSDictionaryOfVariableBindings(viewA,viewB);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[viewA(==50)]" options:0 metrics:nil views:dict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[viewB(==50)]" options:0 metrics:nil views:dict]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[viewA(==50)][viewB(==50)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:dict]];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句