animation完成时如何去除图层?

我正在制作一个iOS应用程序 。 我有几个CALayer对象,最终将被(缩小) animation 删除 。 当animation完成, animationDidStop:finished被调用时,我想从超级视图中删除CALayer对象并将其删除。

  1. 但是我怎么能得到animationDidStop:finishedCALayer对象animationDidStop:finished ? 我会猜测CAanimation有一个指向该图层的指针,但我无法在文档中find它。
  2. 有没有更好的方法来处理这个问题? (其实,我有几个animation对象添加到同一图层,理想情况下,我只想在最后一个animation完成时才移除图层)

创buildanimation并设置委托时,只需将要删除的CALayer与animation一起传递即可。

至于删除所有的animation,你有两个select:

  1. 您可以检查您的CALayer的animation键是否有任何现有的animation。
  2. 您可以使用CAAnimationGroup并将所有animation组合在一起。

看看这个答案是否有帮助: animation完成后执行动作我findanimateWithDuration:animation:完成:比直接使用CALayer更容易使用。 您可以通过完成处理程序链接多个animation,然后删除最后一个图层。 例如:

 [UIView animateWithDuration:1.0 animations:^{ // do first animation in the sequence } completion:^(BOOL finished) { [UIView animateWithDuration:1.0 animations:^{ // do second animation in the sequence } completion:^(BOOL finished) { [UIView animateWithDuration:1.0 animations:^{ // do third animation in the sequence } completion:^(BOOL finished) { // remove layer after all are done }]; }]; }]; 

可能有点混乱,但是你可以将这些重构成自己的方法调用。

一个替代的解决scheme是添加一个图层指针到animation对象的字典,如下所示

 // in some define section #define kAnimationRemoveLayer @"animationRemoveLayer" 

那么,在animationDidStop中,

 - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{ CALayer *lay = [theAnimation valueForKey:kAnimationRemoveLayer]; if(lay){ [lay removeAllAnimations]; [lay removeFromSuperlayer]; } } 

最后,在animation设置中,

 CALAyer * lay = ... ; BOOL shouldRemove = .... ; CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"position"]; anim.delegate = self; if (shouldRemove) [anim setValue:lay forKey:kAnimationRemoveLayer];