为什么约束不适用于UIView但适用于UILabel?

时间:2013-08-07 04:47:42

标签: iphone ios constraints

我在这里有一个简单(完整)的例子,看起来很奇怪,但我肯定只是错过了一些小东西......对吧?你能帮忙调试下面的简单代码吗?这段代码使得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];

3 个答案:

答案 0 :(得分:5)

嗯,行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];

答案 1 :(得分:4)

答案很简单。某些对象,如UILabel,根据其包含的文本具有内在大小,UIViews则没有。因此,由于您没有为UIView设置大小,因此它的大小为0.您需要添加大小约束,或将视图固定到其超级视图的侧面(或同一视图层次结构中的其他视图)。

答案 2 :(得分:0)

作为替代方案,设置所有4个约束(左,右,上,下)也可以解决问题。然后调整宽度和高度,并相应地拉伸UIView。请注意,必须设置所有四个约束。

相关问题