2013-08-07 107 views
2

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

回答

4

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

完美,谢谢你。 –

4

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

+0

我以为框架给了它“大小”......? –

+1

@ user273312当您使用自动布局时,您不应设置任何框架。 – rdelmar

0

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

相关问题