我在这里有一个简单的(完整的)示例,这看起来很奇怪,但是可以肯定我只是缺少了一些小东西...对吗?您可以帮助调试以下简单代码吗?这段代码使aView消失了,但是当我将aLabel放在aView所在的约束中时,它可以完美地工作。为什么?感谢您的输入,这对我来说似乎很疯狂。
奥斯丁
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 30)];
aView.backgroundColor = [UIColor redColor];
aView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:aView];
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 30)];
aLabel.backgroundColor = [UIColor redColor];
aLabel.text = @"Label";
aLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:aLabel];
NSLayoutConstraint *myConstraint =[NSLayoutConstraint
constraintWithItem:aView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1.0
constant:0];
[self.view addConstraint:myConstraint];
myConstraint =[NSLayoutConstraint
constraintWithItem:aView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
[self.view addConstraint:myConstraint];
最佳答案
好吧,这行aView.translatesAutoresizingMaskIntoConstraints = NO;
正在使视图的大小为零。.因此,您必须添加以下代码行:
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100];
[aView addConstraint:widthConstraint];
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
[aView addConstraint:heightConstraint];
关于iphone - 为什么约束不适用于UIView但适用于UILabel?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18094879/