簡單的處理:我想使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]];
這就是我得到:
如果我設置multiplier
到1.0
,那麼視圖的寬度是它的父的一半。但爲什麼呢?
在'self.view'上放置背景色可能會很有用,只是爲了確保它的大小與您期望的相同。 –
完成後,我更新了問題和屏幕截圖。這是一個新鮮的UIViewController,所以'self.view'應該有默認的尺寸。 – Eric
此代碼在哪裏調用? viewDidLoad中?一個單獨的方法?如果在viewDidLoad之後調用它,請嘗試調用[self.view layoutIfNeeded]。 –