2013-08-07 102 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將相應地拉伸。請注意,必須設置所有四個約束。

相關問題