我在這裏有一個簡單的(完整的)例子,這看起來很奇怪,但我肯定只是缺少一些小東西......對吧?你可以幫助調試下面的簡單代碼。這段代碼使得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];
完美,謝謝你。 –