【问题标题】:What is the difference between "setNeedsUpdateConstraints" and "layoutIfNeeded"? When would they be called?“setNeedsUpdateConstraints”和“layoutIfNeeded”有什么区别?他们什么时候被召唤?
【发布时间】:2015-11-09 11:03:53
【问题描述】:

根据设备方向,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];
}

【问题讨论】:

    标签: ios rotation autolayout orientation nslayoutconstraint


    【解决方案1】:

    如果您更改了一些会改变约束的条件(如偏移或框架),请调用 setNeedsUpdateConstraints。

    然后系统将调用 updateConstraints 作为其正常布局传递的一部分。在需要约束之前一次性更新所有约束可确保在布局传递之间对视图进行多项更改时,您不会不必要地重新计算约束。

    如果您需要更新约束后的任何操作立即生效,请在其后使用 layoutIfNeeded。

    因此,您需要先调用 setNeedsUpdateConstraints,一旦完成,您需要调用 layoutIfNeeded,因为它会在绘制之前强制子视图的布局,以便更改的约束相应地反映在视图中。

    【讨论】:

    • 谢谢。我根据设备的方向更新了大部分约束的constant 属性,并再次创建了一些我需要调整它们的multiplier 的约束。那么应该调用什么方法呢?还是我应该两个都打电话?
    • 调用 layoutIfNeeded 就足够了。
    猜你喜欢
    • 2021-09-23
    • 2019-11-24
    • 2021-08-10
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多