在具有自动布局约束的UIScrollView内部动画UIView

时间:2015-09-22 08:04:08

标签: ios objective-c animation uiscrollview autolayout

我在ViewController中放置了一个UIScrollView,我已经给了它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];

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

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

2 个答案:

答案 0 :(得分:3)

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

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

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

或者,您可以使用视图的转换属性并为其设置动画以达到您想要的效果,因为我认为您只需要类似于演示动画的内容。那么你不必修改约束。 你可以这样做:

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

答案 1 :(得分:0)

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

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