繁体   English   中英

使用自动布局约束在UIScrollView内部动画UIView

[英]Animating UIView inside of a UIScrollView with autolayout constraints

我有一个UIScrollView放在一个ViewController里面,我已经给了AutoLayout约束,所有这些都满足了。 scrollView包含大约20个UIButton子视图。 我也给了他们autolayout约束,他们都满意。

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

    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];

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

有没有其他方法可以做到这一点,或者我应该忽略错误消息,然后继续使用它?

使用自动布局时,请勿修改框架。

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

它通过设置setTranslatesAutoresizingMaskIntoConstraints工作,因为然后设置框架会导致创建约束。 这些最终会与您现有的约束冲突并导致约束警告。

或者,您可以使用视图的转换属性并为其设置动画以实现所需的效果,因为我认为您只需要类似于演示动画的内容。 然后您不必修改约束。 你会做的事情如下:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM