如何在完成之前中断UIView动画?

Arm*_*and 2 animation uiview ios

我正在使用[UIView animateWithDuration ...]来显示我的应用程序的每个页面的文本.每个页面都有自己的文本.我正在刷卡以在页面之间导航.我正在使用1秒的溶解效果,在显示页面后让文本淡入.

问题在于:如果我在1秒内(在此期间文本渐渐消失)中滑动,则当下一页出现并且2个文本将重叠(前一个和当前)时,动画将完成.

我想要实现的解决方案是,如果我碰巧在它发生时滑动,就会中断动画.我无法实现它.[self.view.layer removeAllAnimations]; 不适合我.

这是我的动画代码:

   - (void) replaceContent: (UITextView *) theCurrentContent withContent: (UITextView *) theReplacementContent {

    theReplacementContent.alpha = 0.0;
    [self.view addSubview: theReplacementContent];


    theReplacementContent.alpha = 0.0;

    [UITextView animateWithDuration: 1.0
                              delay: 0.0
                            options: UIViewAnimationOptionTransitionCrossDissolve
                         animations: ^{
                             theCurrentContent.alpha = 0.0;
                             theReplacementContent.alpha = 1.0;
                         }
                         completion: ^(BOOL finished){
                             [theCurrentContent removeFromSuperview];
                             self.currentContent = theReplacementContent;
                             [self.view bringSubviewToFront:theReplacementContent];
                         }];

   }
Run Code Online (Sandbox Code Playgroud)

你们知道如何使这项工作?你知道其他任何解决这个问题的方法吗?

Tob*_*obi 11

您无法直接取消通过创建的动画+animateWithDuration....你想要做的是用一个新的动画替换正在运行的动画.

您可以编写以下方法,当您想要显示下一页时调用它:

- (void)showNextPage
{
    //skip the running animation, if the animation is already finished, it does nothing
    [UIView animateWithDuration: 0.0
                          delay: 0.0
                        options: UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionBeginFromCurrentState
                     animations: ^{
                         theCurrentContent.alpha = 1.0;
                         theReplacementContent.alpha = 0.0;
                     }
                     completion: ^(BOOL finished){
                         theReplacementContent = ... // set the view for you next page
                         [self replaceContent:theCurrentContent withContent:theReplacementContent];
                     }];
}
Run Code Online (Sandbox Code Playgroud)

注意附加UIViewAnimationOptionBeginFromCurrentState传递给options:.它的作用是,它基本上告诉框架拦截受影响属性的任何正在运行的动画并用它替换它们.通过设置duration:0.0,可以立即设置新值.

completion:然后,您可以在块中创建和设置新内容并调用replaceContent:withContent:方法.