同时更新多个视图约束

10

在运行时有没有一种方法可以告诉自动布局引擎,我将同时更改一个视图上的多个约束条件?我经常遇到这样的情况,即我更新约束条件的顺序很重要,因为尽管最终所有约束条件都满足,但先更改其中一个约束条件的常量会抛出“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;
}
当视图上发生滑动手势时,我会创建一个新视图并将其放置在左侧或右侧,具体取决于滑动的方向。然后,我会更新约束并进行动画处理,使新的视图"推出"旧视图。
- (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;
            }];
}

当滑动手势的方向是UISwipeGestureRecognizerDirectionLeft时,这个功能运作良好,但是当方向是UISwipeGestureRecognizerDirectionRight时,异常会在此处抛出

这段代码在UISwipeGestureRecognizerDirectionLeft方向正常工作,但在UISwipeGestureRecognizerDirectionRight方向时会出现异常

    self.myView.leadingConstraint.constant = finalX;

如果我按相反的顺序检查方向并更新约束条件,一切都正常,异常就不会被抛出:

if(swipeDirection == UISwipeGestureRecognizerDirectionLeft)
{
    self.myView.leadingConstraint.constant = finalX;
    self.myView.trailingConstraint.constant = finalX;
}
else
{
    self.myView.trailingConstraint.constant = finalX;
    self.myView.leadingConstraint.constant = finalX;
}

我明白为什么会抛出异常,但似乎我们应该能够更改多个约束参数并让自动布局引擎知道我们将要这样做,而不是立即尝试满足约束并抛出异常。

有没有一种方法告诉自动布局引擎我在更改多个约束,然后在完成更改时再运行它,或者我必须按照这种方式执行?在我完成更改时,所有事情实际上都会没问题,所以我觉得在更新约束的顺序很重要是很愚蠢的。

编辑
经过进一步调查,我发现造成顺序关系的根本原因是myView中添加了一个子视图,其中有一个约束规定它的前缘距离myView的前缘10pt。如果我对新常量进行调整以解决此问题,则不再存在约束冲突,也不会出现异常。

self.myView.leadingConstraint.constant = finalX+25; // Just arbitrary number that happened to work
self.myView.trailingConstraint.constant = finalX;

问题出在当从左向右滑动时,新的限制条件导致myView的宽度收缩为0。很明显,一个宽度为0的视图中没有足够的空间添加一个10pt的前向边缘约束到一个子视图中。改变常量的顺序相反地,首先通过增加尾边来扩展视图,然后再通过减少前边缘来缩小视图。

更有理由告诉自动布局系统我们将进行多次更改的方法。

6个回答

8
为了同时更新多个约束条件,请覆盖updateConstraints方法,并添加您的更新逻辑,然后调用setNeedsUpdateConstraints以触发更新。这段话来自于苹果公司的自动布局指南 > 高级自动布局 > 修改约束条件

要批量更改,请勿直接更改约束条件,而是在保存约束条件的视图上调用setNeedsUpdateConstraints方法。然后,重写该视图的updateConstraints方法以修改所需的约束条件。

使用此方法更新约束条件不太直观,因此建议在尝试此路线之前仔细阅读文档。

很好的回答,当我尝试逐个更新两个约束时,出现了模糊布局错误,但是当我开始使用updateConstraints时,问题就消失了。 - kelin

4
首先,你可能过度约束了myView相对于其父视图的限制,使得约束无法让其滑动。你已经固定了它的前缘和后缘,再加上垂直约束时,还使用了NSLayoutFormatAlignAllCenterX来固定它的中心。
除此之外,也许更好的思考方式是,拥有两个必须同步更新的约束表明你正在使用错误的约束。你可以有一个前缘的约束,然后再有一个使得myView的宽度等于self.view宽度的约束。这样,你只需要调整前缘约束的常量,两侧就会相应地移动。
另外,你正在使用-setFrame:,这在自动布局中是不可行的。你应该用约束来进行动画处理。你应该为newView设置约束,使其前缘或后缘(根据情况而定)等于myView的相邻边缘,其宽度等于self.view的宽度。然后,在动画块中,改变决定myView位置的约束的常量(间接地改变newView的约束),将它们一起滑动。在完成处理程序中,在newView上安装一个约束,以保持其前缘与self.view重合,因为它是新的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];
        }];

编辑以更直接地回答问题:没有在公共API中批量约束更新的方法,使得引擎在添加或通过设置其常量突变时不会一次检查它们。


1
谢谢您的回答,但那并没有回答我的问题,我的问题是:“有没有一种方法告诉自动布局我即将更改多个约束条件。” - Jordan
如果您在指定(否则)垂直约束时省略NSLayoutFormatAlignAllCenterX选项,您确定仍会收到异常吗?我不确定异常是否仅因为您设置前导和尾随常量的顺序而产生。 - Ken Thomases
是的,我很确定。在这种情况下,options:设置为什么并不重要。因为只有一个视图,它的所有边缘都固定在父视图的边缘上,它会自动与所有内容对齐。将其更改为其他内容仍然会导致抛出异常。我已经发现了顺序为什么很重要的根本原因。请参见我对原始问题的编辑。 - Jordan
我已经编辑了我的答案,以更直接地回答你的问题。;-P - Ken Thomases
好的,我会接受它。感谢对话。此外,我确实喜欢您的解决方案,只需更改一个约束即可获得幻灯片动画。也感谢您这一点。 - Jordan

1
此外,您可以将其中一个约束条件设置为非活动状态,然后在正确设置所有内容后再重新激活它: self.constraint.active = false;

0

基于 Dannie P 的回答:

// before the updates
[self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.active = NO;
        }];

// perform updates

// after the updates
[self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.active = YES;
        }];

0

我遇到了一个类似的问题,需要以尽可能少的代码编程方式将一个视图(具有固定高度)粘贴到其父视图的顶部XOR底部。关键在于找到一种方法来切换两个互斥的强制约束条件(这意味着两者不能同时激活,但其中一个是强制性的)。

我的解决方案是在IB中降低一个约束条件的优先级。因此,当停用一个活动约束条件而另一个未被激活时(反之亦然),不会触发约束问题。

let isViewUpward = pointInView.y < view.bounds.height / 2
topConstraint.isActive = isViewUpward
bottomConstraint.isActive = !isViewUpward

0
这对我有效:
NSLayoutConstraint.deactivate([constraint1, constraint2])
constraint1.constant -= k
constraint2.constant += k
NSLayoutConstraint.activate([constraint1, constraint2])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接