在iOS中等待动画完成?

3

我希望在动画完成后执行doSomethingElse。另一个限制是动画代码的持续时间可能不同。我该怎么做?谢谢!

-(void) doAnimationThenSomethingElse {
  [self doAnimation];
  [self doSomethingElse];
}

举个例子,这个不起作用:

animationDuration = 1;
[UIView animateWithDuration:animationDuration
    animations:^{
      [self doAnimation];
    } completion:^(BOOL finished) {
      [self doSomethingElse];
    }
];

2
你提供的信息不足以解决你的问题。请看下面我的回答,要想得到你想要的行为,你必须能够看到执行动画的代码(这里由doAnimation封装)。 - isaac
5个回答

24

当您不是动画的作者时,可以使用事务完成块在动画结束时获取回调:

[CATransaction setCompletionBlock:^{
     // doSomethingElse
}];
// doSomething

7

使用块级动画:

[UIView animateWithDuration:animationDuration
    animations:^{
        // Put animation code here
    } completion:^(BOOL finished) {
        // Put here the code that you want to execute when the animation finishes
    }
];

我没有具体的持续时间,见上文。 - Sebastian Oberste-Vorth
我不知道之前的持续时间,这取决于doAnimation函数,它有点随机。 - Sebastian Oberste-Vorth
completion:^(BOOL finished) 的整个意义在于它在 animations 块之后运行。这是最好的方式。 - bobobobo
@SebastianOberste-Vorth 嗯?为什么会有两个踩?这个回答是正确的...如果你还不理解我的意思,却又无法提供一些合理的背景信息,那并不是我的错。"不起作用"远远不够有帮助... "为什么?为什么不起作用?它的行为如何?你期望什么?" 学会正确地提问,否则我就不能费力去帮忙了。 - user529758
因为这个方法对我非常有效,所以我点了赞! - Michael Hogenson
显示剩余5条评论

2
您需要能够访问您正在运行的动画的特定实例,以便为每个动画协调完成操作。在您的示例中,[self doAnimation] 不向我们公开任何动画,因此您提供的内容无法“解决”您的问题。
有几种方法可以实现您想要的效果,但这取决于您处理的动画类型。
正如其他答案所指出的那样,在视图上执行动画后执行代码的最常见方法是传递一个 completionBlock: animateWithDuration:completion: 另一种处理属性更改动画的方法是在事务范围内设置 CATransaction 完成块。
然而,这些特定的方法基本上是用于对视图的属性或层次结构进行动画处理。当您的动画涉及视图及其属性时,这是推荐的方法,但它并不涵盖您可能在 iOS 中找到的所有类型的动画。从您的问题中,并不清楚您使用的是哪种动画(或者如何、为什么使用),但如果您实际上正在触摸 CAAnimations 的实例(关键帧动画或一组动画),您通常会设置一个委托:
CAAnimation *animation = [CAAnimation animation];
[animation setDelegate:self];
[animatedLayer addAnimation:animation forKeyPath:nil];

// Then implement the delegate method on your class
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
    // Do post-animation work here.
}

重点在于,您的完成处理方式取决于动画的实现方式。在这种情况下,我们无法看到后者,因此无法确定前者。

0

从您的评论中,我建议您:

-(void) doAnimation{
    [self setAnimationDelegate:self];
    [self setAnimationDidStopSelector:@selector(finishAnimation:finished:context:)];
    [self doAnimation];
}

- (void)finishAnimation:(NSString *)animationId finished:(BOOL)finished context:(void *)context {
    [self doSomethingElse];
}

如果没有在UIView动画块内调用,setAnimationDidStopSelector:将不起作用。 - isaac
你说得对,已经更新了代码。 - Efesus

0

所有这些都具有属性“animateWithDuration”,在代码执行之前我不知道。 - Sebastian Oberste-Vorth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接