我在这里有一个简单的(完整的)例子,这看起来很奇怪,但我肯定只是缺少一些小东西......对吧?你可以帮助调试下面的简单代码。这段代码使得aView消失了,但是如果我把aLabel放在aView的约束中,它就完美了。为什么?感谢您的任何意见,这对我来说似乎很疯狂。为什么约束不适用于UIView,但适用于UILabel?
奥斯汀
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];
完美,谢谢你。 –