停止无限约束动画

Stop Infinite Constraint Animation

我一直在努力stop/remove一个无限约束动画启动后。基本上我有一个盒子,它的约束与主视图的高度相同,乘数为 0.5。该框应该通过将乘数更改为 0.8 并通过 UIViewAnimationOptionAutoreverse | 变回 0.5 来增大和缩小 | UIViewAnimationOptionRepeat 。由于 multiplier 是只读的,因此对其进行动画处理的唯一方法是删除约束并使用 a multiplier 将其添加回去。盒子动画效果很好,但使用经典方法停止 UIView 动画的停止方法似乎根本不起作用。

如果我对 box.transofrm = CGAffineTransformMakeScale(1.0f, 0.8f) 设置动画,我可以停止动画,但这样做不是在自动布局时对约束本身设置动画不建议启用。

这是我的代码

// wired equal height constraint between box and view with multiplier 0.5
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *boxEqualHeightConstraint;

.

-(void)startAnimation {
        // animation starts fine
        [self.view removeConstraint:self.boxEqualHeightConstraint]; // remove multi 0.5
        self.boxEqualHeightConstraint = [NSLayoutConstraint constraintWithItem:self.box
                                                               attribute:NSLayoutAttributeHeight
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.view
                                                               attribute:NSLayoutAttributeHeight
                                                              multiplier:0.8
                                                                constant:0];

        [self.view addConstraint:self.boxEqualHeightConstraint]; // add multi 0.8
        [self.view layoutIfNeeded];
        [UIView animateWithDuration:1.0f delay:0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat animations:^{
           [self.view layoutIfNeeded];

        } completion:nil];

    }

-(void)stopAnimations {

    [self.view.layer removeAllAnimations]; // not working
    [self.box.layer removeAllAnimations]; // not working


    // I tried replacing the constraint animation, but it is still growing and shrinking indefinitely.
    [self.view removeConstraint:self.boxEqualHeightConstraint];
    self.boxEqualHeightConstraint = [NSLayoutConstraint constraintWithItem:self.box
                                                           attribute:NSLayoutAttributeHeight
                                                           relatedBy:NSLayoutRelationEqual
                                                              toItem:self.view
                                                           attribute:NSLayoutAttributeHeight
                                                          multiplier:0.5
                                                            constant:0];

    [self.view addConstraint:self.boxEqualHeightConstraint];

    [self.view layoutIfNeeded];
    [UIView animateWithDuration:1.0f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];

}

我找到了动画不会停止的原因。我的 self.box(这是一个 UIButton)包含一个图像。

在 removeAllAnimations 之后仍在动画的只是框内的图像,而不是框本身。

所以要停止它,请这样做:

[self.box.imageView.layer removeAllAnimations];