2013-12-09 28 views
1

簡單的處理:我想使UIView的寬度減半。這裏是我的代碼:自動佈局 - 使視圖的尺寸依賴於另一個視圖的尺寸

//Display a red rectangle: 
UIView *redBox = [[UIView alloc] init]; 
[redBox setBackgroundColor:[UIColor redColor]]; 
[redBox setTranslatesAutoresizingMaskIntoConstraints:NO]; 
[self.view addSubview:redBox]; 

//Make its height equal to its superview's, 
//minus standard spacing on top and bottom: 
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[redBox]-|" options:0 metrics:nil views:@{@"redBox": redBox}]; 
[self.view addConstraints:constraints]; 

//Make its width half of its superviews's width (the problem): 
NSLayoutConstraint *constraint = [NSLayoutConstraint 
            constraintWithItem:redBox 
            attribute:NSLayoutAttributeWidth 
            relatedBy:NSLayoutRelationEqual 
            toItem:self.view 
            attribute:NSLayoutAttributeWidth 
            multiplier:0.5 
            constant:0.0 
            ]; 

[self.view addConstraint:constraint]; 

[self.view setBackgroundColor:[UIColor blueColor]]; 

這就是我得到:

enter image description here

如果我設置multiplier1.0,那麼視圖的寬度是它的父的一半。但爲什麼呢?

+0

在'self.view'上放置背景色可能會很有用,只是爲了確保它的大小與您期望的相同。 –

+0

完成後,我更新了問題和屏幕截圖。這是一個新鮮的UIViewController,所以'self.view'應該有默認的尺寸。 – Eric

+0

此代碼在哪裏調用? viewDidLoad中?一個單獨的方法?如果在viewDidLoad之後調用它,請嘗試調用[self.view layoutIfNeeded]。 –

回答

1

問題可能是您的紅框視圖受到了不足的限制。你已經給它一個寬度,但沒有什麼可以告訴它它應該在哪裏水平放置。由於它應該是超視圖寬度的一半,因此它可以選擇將自己定位在超視圖的左半邊。或者右邊一半。或者中間。你沒有指定,所以框架就會選擇一些東西。

在這種情況下,它看起來像是選擇將紅框的中心與超視圖的左邊緣對齊。這似乎是一個奇怪的選擇,但同樣,你沒有指定任何東西。它可以選擇任何想要的。

添加另一個將水平放置視圖的約束。這應該解決問題。

+0

你說得對。我的代碼**是**給子視圖正確的大小,但它的一部分是在視圖的框架之外。 我不得不添加此: '約束= [NSLayoutConstraint constraintWithItem:REDBOX 屬性:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view 屬性:NSLayoutAttributeLeading 乘數:1.0 常數:0.0 ];' – Eric