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

标签 ios animation uiview

我正在使用 [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];
                         }];

   }

你们知道怎么做吗?您知道解决此问题的其他方法吗?

最佳答案

您不能直接取消通过+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];
                     }];
}

注意额外的 UIViewAnimationOptionBeginFromCurrentState 传递给 options:。它的作用是,它基本上告诉框架拦截受影响属性的任何正在运行的动画,并用这个替换它们。 通过将 duration: 设置为 0.0,新值会立即设置。

completion: block 中,您可以创建和设置新内容并调用您的 replaceContent:withContent: 方法。

关于ios - 如何在完成之前中断 UIView 动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15693795/

相关文章:

iphone - 如何将ios更新到特定版本

ios - 在 beginBackgroundTaskWithExpirationHandler 中调用 NSTImer 的选择器方法两次

java - Swing 动画暂停和恢复

wpf - 如何使用动画改变网格的大小?

iPhone UIView - 调整框架大小以适合 subview

objective-c - 实现一个将 block 用作回调的方法

javascript - 图像闪烁及预防。正确的编码标准

ios - 在另一个类中调用函数(包含变量)

swift - 约束应用的时间

ios - 从 SKAction 播放音乐