同时更新多个视图约束

Jor*_*ndo 8 objective-c ios autolayout

有没有办法告诉自动布局引擎,在运行时,我将同时更改视图上的多个约束?我一直遇到这样一种情况,即我更新约束的顺序很重要,因为即使完成所有约束条件的所有操作都满足,但在另一个之前更改常量会抛出LAYOUT_CONSTRAINTS_NOT_SATISFIABLE异常(或任何异常)实际上被称为...)

这是一个例子.我创建并添加一个视图到我当前的视图并设置一些约束.我正在保存前导和后沿约束,所以我可以稍后更改它们的常量.

- (MyView*)createMyView
{
    MyView* myView = [[MyView alloc init];

    [myView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.mainView addSubview:myView];

    NSDictionary* views = @{@"myView" : myView};
    NSLayoutConstraint* leading = [NSLayoutConstraint constraintWithItem:myView
                                                               attribute:NSLayoutAttributeLeading
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.view
                                                               attribute:NSLayoutAttributeLeading
                                                              multiplier:1.0f
                                                                constant:0];
    NSLayoutConstraint* trailing = [NSLayoutConstraint constraintWithItem:myView
                                                                attribute:NSLayoutAttributeTrailing
                                                                relatedBy:NSLayoutRelationEqual
                                                                   toItem:self.view
                                                                attribute:NSLayoutAttributeTrailing
                                                               multiplier:1.0f
                                                                 constant:0];
    myView.leadingConstraint = leading;
    myView.trailingConstraint = trailing;

    [self.view addConstraints:@[leading, trailing]];

    NSString* vflConstraints = @"V:|[myView]|";
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vflConstraints
                                                                      options:NSLayoutFormatAlignAllCenterX
                                                                      metrics:nil
                                                                        views:views]];
    return myView;
}
Run Code Online (Sandbox Code Playgroud)

当视图上的滑动手势触发时,我会根据滑动的方向创建一个或另一侧的新视图.然后我更新约束和动画,以便新的传入视图将旧视图"推"出视图.

- (void)transitionToCameraView:(MyView*)newCameraView
                swipeDirection:(UISwipeGestureRecognizerDirection)swipeDirection
{
    // Set new view off screen before adding to parent view
    float width = self.myView.frame.size.width;
    float height = self.myView.frame.size.height;
    float initialX = (swipeDirection == UISwipeGestureRecognizerDirectionLeft) ? width : -width;
    float finalX = (swipeDirection == UISwipeGestureRecognizerDirectionLeft) ? -width : width;
    float y = 0;

    [newView setFrame:CGRectMake(initialX, y, width, height)];
    [self.mainView addSubview:newView];

    self.myView.leadingConstraint.constant = finalX;
    self.myView.trailingConstraint.constant = finalX;

    // Slide old view out and new view in
    [UIView animateWithDuration:0.4f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction
                     animations:^
            {
                [newView setFrame:self.myView.frame];
                [self.myView layoutIfNeeded];
            }
                     completion:^(BOOL finished)
            {
                [self.myView removeFromSuperview];
                self.myView = newView;
            }];
}
Run Code Online (Sandbox Code Playgroud)

滑动方向为UISwipeGestureRecognizerDirectionLeft时,此方法正常,但是当它是UISwipeGestureRecognizerDirectionRight时,异常会被抛出

    self.myView.leadingConstraint.constant = finalX;
Run Code Online (Sandbox Code Playgroud)

如果我检查方向并以相反的顺序更新约束,一切都很好,并且不会抛出异常:

if(swipeDirection == UISwipeGestureRecognizerDirectionLeft)
{
    self.myView.leadingConstraint.constant = finalX;
    self.myView.trailingConstraint.constant = finalX;
}
else
{
    self.myView.trailingConstraint.constant = finalX;
    self.myView.leadingConstraint.constant = finalX;
}
Run Code Online (Sandbox Code Playgroud)

它对我有意义为什么异常被抛出,但似乎更改多个约束参数是我们应该能做的事情,并让自动布局引擎知道我们将要做到这一点,而不是立即试图满足约束和呕吐.

有没有办法告诉自动布局引擎我正在对多个约束进行更改,然后告诉它在我完成后再次运行,或者我是不是这样做了?当我完成更改时,当所有事情都变得很好时,让我更新约束的顺序对我来说似乎真的很愚蠢.

编辑
经过进一步调查,我发现订单重要的根本原因是myView添加了一个子视图,其中有一个约束,指明它的前沿距离myView的前沿是10pt.如果我对新常量进行调整和调整以解决这个问题,则不再存在约束冲突,也没有例外.

self.myView.leadingConstraint.constant = finalX+25; // Just arbitrary number that happened to work
self.myView.trailingConstraint.constant = finalX;
Run Code Online (Sandbox Code Playgroud)

出现问题的原因是从左向右滑动时的新约束将myView折叠为宽度为0.显然,在宽度为0的视图中没有足够的空间来向子视图添加10pt前沿约束.相反,以相反的顺序更改常量,首先通过增加后沿来扩大视图,然后通过减小前沿将其再次缩小.

更有理由告诉自动布局系统我们将进行多项更改.

yoo*_*ood 7

要同时更新多个约束,请覆盖updateConstraints您的更新逻辑并调用setNeedsUpdateConstraints触发更新。从 Apple 的自动布局指南 > 高级自动布局 > 更改约束

要批量更改,而不是直接进行更改,请调用 setNeedsUpdateConstraints持有约束的视图上的方法。然后,覆盖视图的updateConstraints方法以修改受影响的约束。

以这种方式更新约束并不那么简单,所以我建议您在沿着这条路线前进之前仔细阅读文档。


Ken*_*ses 4

首先,您似乎相对于其超级视图过度约束,myView以至于约束不允许它滑动。您已经固定了它的前缘和后缘,此外,在添加垂直约束时,您还通过指定 固定了它的中心NSLayoutFormatAlignAllCenterX

除此之外,也许更好的思考方式是,拥有两个必须同步更新的约束表明您使用了错误的约束。您可以对前缘有一个约束,然后对myView的宽度等于 的宽度进行约束self.view。这样,您只需调整前导约束的常数,两条边就会随之移动。

另外,您正在使用-setFrame:,这是自动布局的禁忌。您应该对约束进行动画处理。您应该设置约束newView,使其前缘或后缘(视情况而定)等于 的相邻边缘,myView并且其宽度等于 的宽度self.view。然后,在动画块中,更改确定 的位置的约束常量myView(以及间接的newView)以将它们滑动到一起。在完成处理程序中,安装一个约束newView以保持其前缘与self.views 重合,因为它是新的myView

BOOL left = (swipeDirection == UISwipeGestureRecognizerDirectionLeft);
float width = self.myView.frame.size.width;
float finalX = left ? -width : width;
NSString* layout = left ? @"[myView][newView(==mainView)]" : @"[newView(==mainView)][myView]";
NSDictionary* views = NSDictionaryOfVariableBindings(newView, myView, mainView);

[self.mainView addSubview:newView];
[self.mainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:layout
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];
[self.mainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|newView|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:views]];
[self.mainView layoutIfNeeded];

// Slide old view out and new view in
[UIView animateWithDuration:0.4f
                      delay:0.0f
                    options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction
                 animations:^
        {
            self.myView.leadingConstraint.constant = finalX;
            [self.myView layoutIfNeeded];
        }
                 completion:^(BOOL finished)
        {
            [self.myView removeFromSuperview];
            self.myView = newView;
            NSLayoutConstraint* leading = [NSLayoutConstraint constraintWithItem:newView
                                                                       attribute:NSLayoutAttributeLeading
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:self.view
                                                                       attribute:NSLayoutAttributeLeading
                                                                      multiplier:1.0f
                                                                        constant:0];
            self.myView.leadingConstraint = leading;
            [self.mainView addConstraint:leading];
        }];
Run Code Online (Sandbox Code Playgroud)

编辑以更直接地回答这个问题:不,公共 API 中没有办法批量约束更新,这样引擎就不会在通过设置常量添加或改变它们时一次检查它们。