簡體   English   中英

如何從 animationDidStop 中刪除 CALayer 對象?

[英]How to remove a CALayer-object from animationDidStop?

我正在嘗試學習 iOS/iPhone 的核心動畫。 我的根層包含很多子層(精靈),當它們被移除時應該會旋轉......

我的計划是添加一個旋轉的 animation,然后在調用 animationDidStop 時移除精靈。 問題是精靈層不是animationDidStop的參數!

從 animationDidStop 中找到特定精靈圖層的最佳方法是什么? 有沒有更好的方法讓精靈在被移除時旋轉? (理想情況下我想使用 kCAOnOrderOut 但我無法使其工作)

-(void) eraseSprite:(CALayer*)spriteLayer {
    CABasicAnimation* animSpin = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    animSpin.toValue = [NSNumber numberWithFloat:2*M_PI];
    animSpin.duration = 1; 
    animSpin.delegate = self;
    [spriteLayer addAnimation:animSpin forKey:@"eraseAnimation"];    
}



- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{
    // TODO check if it is an eraseAnimation
    //      and find the spriteLayer

    CALayer* spriteLayer = ??????   
    [spriteLayer removeFromSuperlayer]; 
}

在這里找到了這個答案cocoabuilder但基本上你為正在動畫的 CALayer 的 CABasicAnimation 添加了一個鍵值。

- (CABasicAnimation *)animationForLayer:(CALayer *)layer
{
     CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
     /* animation properties */
     [animation setValue:layer forKey:@"animationLayer"];
     [animation setDelegate:self];
     return animation;
}

然后在 animationDidStop 回調中引用

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
 {
     CALayer *layer = [anim valueForKey:@"animationLayer"];
     if (layer) {
         NSLog(@"removed %@ (%@) from superview", layer, [layer name]);
         [layer removeFromSuperlayer];
     }
 }

你可以有一個`CALayer 類型的iVar iTempSpriteLayer

@property (nonautomic, assign) CALayer* iTempSpriteLayer;

-(void) eraseSprite:(CALayer*)spriteLayer {

    iTempSpriteLayer = spriteLayer;
   ...........................
}


- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{
    // TODO check if it is an eraseAnimation
    //      and find the spriteLayer
    if(iTempSpriteLayer)
      [iTempSpriteLayer removeFromSuperlayer];
    iTempSpriteLayer = nil;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM