0

我在同时为多个 CALayers 设置动画时遇到了一些问题,希望有人能指出我正确的方向。

我的应用程序包含一个 CALayer 数组。每一层的位置设置为(previousLayer.position.y + previousLayer.bounds.height),这基本上将它们布置成类似于表格。然后我有一个方法,每次调用它时,都会在堆栈中添加一个新层并将其 Y 位置设置为 0。然后数组中所有其他层的 Y 位置会偏移新层的高度层(基本上将所有旧层向下推)。

我遇到的问题是在上一个动画完成之前阻止添加新图层。有没有办法判断隐式动画何时完成?或者,如果我使用CABasicAnimationand animationDidFinish,有没有办法告诉哪个对象在animationDidFinish调用时完成了动画?

4

3 回答 3

4

您可以为动画对象上的键设置任意值。这意味着您可以将您正在制作动画的图层与动画相关联,然后在 -animationDidStop:finished: 中查询它:您可以这样创建动画:

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
// set other fields...

[anim setValue:layerToAnimate forKey:@"layer"];

// Start the animation
[layerToAnimate addAnimation:anim forKey:nil];

然后在动画停止时检查该值:

- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag
{
    CALayer *animatedLayer = [animation valueForKey:@"layer"];
    // do something with the layer based on some condition...
    // spin off the next animation...

    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue
                 forKey:kCATransactionDisableActions];
    [animatedLayer setPosition:position];
    [CATransaction commit];
}

这是明确的动画,但它应该给你你需要的东西。

于 2010-06-15T18:03:34.330 回答
2

您可以尝试将您的代码包含在CATransaction. 这是在 Swift 3 中的样子:

CATransaction.begin()
CATransaction.setCompletionBlock({
  // run after the animations
})
// animtations
CATransaction.commit()
于 2016-08-19T01:46:24.397 回答
0

事实证明,我没有将 CABasicAnimation 直接添加到 CALayer 中,而是将其添加到图层的“动作”字典中……这在动画结束后将图层留在其最终位置,但仍调用“animationDidFinish”方法.

-(void)startAnimation {
    if(!animating){
        animating = YES;
        for(int i=0; i<[tweets count]; i++) {
            //get the layer
            CETweetLayer *currentLayer = [tweets objectAtIndex:i];

            //setup the orgin and target y coordinates
            float targetY = currentLayer.position.y + offset;

        //setup the animation
        CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
        anim.delegate = self;
        currentLayer.actions = [NSDictionary dictionaryWithObject:anim forKey:@"position"];
        currentLayer.position = CGPointMake(self.bounds.size.width/2, targetY);
     }
    }
}

进而...

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    animating = NO; 
}
于 2010-06-26T19:49:19.963 回答