![](/img/trans.png)
[英]Why would layoutIfNeeded be called upon scrolling the uitableviewcontroller?
[英]What is the difference between “setNeedsUpdateConstraints” and “layoutIfNeeded”? When would they be called?
對於自動autolayout
約束,我有不同的值,具體取決於設備的方向。 我以這種方式更新約束:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if ((orientation == UIInterfaceOrientationPortrait) || (orientation == UIInterfaceOrientationPortraitUpsideDown)) {
self.backgroundView.image = [UIImage imageNamed:@"landscape.jpg"];
[self updateLandscapeConstraints];
}
else if ((orientation == UIInterfaceOrientationLandscapeLeft) ||
(orientation == UIInterfaceOrientationLandscapeRight)) {
self.backgroundView.image = [UIImage imageNamed:@"portrait.jpg"];
[self updatePortraitConstraints];
}
}
在某些帖子中,我看到在應用約束更新后調用了[self.view setNeedsUpdateConstraints]
,而在其他帖子中,則調用了[self.view layoutIfNeeded]
。 有什么區別?
提前致謝
編輯:我以此方式更新約束,對嗎?:
- (void)updateLandscapeConstraints
{
[self.view layoutIfNeeded];
self.passwordViewHeight.constant = 34.0;
self.usernameViewHeight.constant = 34.0;
[self.view removeConstraint:self.registrationButtonEqualWidth];
self.registrationButtonEqualWidth = [NSLayoutConstraint constraintWithItem:self.registrationButton
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.backgroundView
attribute:NSLayoutAttributeWidth
multiplier:0.6
constant:0.0];
[self.view addConstraint:self.registrationButtonEqualWidth];
[self.view layoutIfNeeded];
}
如果更改了某些條件(例如偏移量或框架),這些條件會更改約束,請調用setNeedsUpdateConstraints。
然后,系統將調用updateConstraints作為其常規布局傳遞的一部分。 在需要約束之前立即全部更新約束,以確保在布局遍之間兩次對視圖進行多次更改時,您不必不必要地重新計算約束。
如果在更新約束后需要任何操作以立即生效,請在其后使用layoutIfNeeded。
因此,您需要先調用setNeedsUpdateConstraints,一旦完成,您需要調用layoutIfNeeded,因為它會在繪制之前強制子視圖的布局,從而使更改的約束相應地反映在視圖中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.