使用自动布局约束在 UIScrollView 中动画化 UIView

Animating UIView inside of a UIScrollView with autolayout constraints

我在 ViewController 中放置了一个 UIScrollView,我已经为其设置了 AutoLayout 约束并且所有约束都得到了满足。 scrollView 包含大约 20 个 UIButton 子视图。我也给了他们自动布局约束,他们也都很满意。

我需要做的是在首次启动视图时为这些按钮设置动画。这是我的动画代码

    for (UIButton *button in [scrollView subviews]) {
    CGRect mainFrame = [button frame];
    [UIView animateWithDuration:0.0 animations:^{
        button.frame = CGRectMake(button.center.x, button.center.y, 0, 0);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 delay:0.5 usingSpringWithDamping:0.3 initialSpringVelocity:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
            button.frame = mainFrame;
        } completion:^(BOOL finished) {
        }];
    }];

}

当我使用这段代码时,子视图没有动画。 但是当我设置

[button setTranslatesAutoresizingMaskIntoConstraints:YES];

有效。但是这次我得到了无法同时满足约束的错误。

有没有其他方法可以做到这一点,还是我应该忽略错误消息并继续它?

您应该为约束中的常量值设置动画,而不是为每个按钮的框架设置动画。为每个要设置动画的约束创建内部属性,然后使用 UIViewanimateWithDuration。例如:

self.myConstraint.constant = 10;
[button setNeedsUpdateConstraints];
[UIView animateWithDuration:1 animations:^{
  [button layoutIfNeeded];
}];

使用自动布局时不要修改框架。

您应该修改约束以实现动画并在动画块中调用[yourView layoutIfNeeded]

它通过设置 setTranslatesAutoresizingMaskIntoConstraints 来工作,因为设置框架会导致创建约束。这些最终与您已经存在的约束冲突并导致约束警告。

或者,您可以使用视图的变换 属性 并为其设置动画以达到您想要的效果,因为我认为您只需要演示动画之类的东西。然后你不必修改约束。 你会做这样的事情:

[UIView animateWithDuration:1.0 animations:^{
  button.transform = CGAffineTransformMakeTranslation(10.0, 10.0);
}];