动画停止后逐一删除CALayers

时间:2011-08-03 04:06:22

标签: stack calayer

当用户点击“飞入”时,我想制作一堆硬币 - >硬币将在弯曲的路径中飞行并排列成一堆。我用了CALayer:

CALayers *coinLayer = [CALayers layer];
coinLayer.backgroundColor = [UIColor clearColor].CGColor;
coinLayer.contents = (id)[UIImage imageNamed:@"head coin.png"].CGImage;
coinLayer.frame = CGRectMake(100, 500 - (10*coin), 55, 21);
coin = coin + 1;
[self.view.layer addSublayer:coinLayer];

我已经完成了弯曲路径中的动画,但如果我以这种方式添加我的coinLayer,那么如果我不将它添加到数组中,我该如何删除CALayer。

例如,我有一堆数字,我在堆栈中添加1,2,3,4,5,6,7,8,9。当删除4个数字时,它将从9减少到8 ...逐个减少到6。在我的代码中,当我在视图的图层中添加CALayer时,这是正确的吗?如何像示例一样逐个删除图层?

非常感谢你!

1 个答案:

答案 0 :(得分:1)

不是创建和删除CALayer对象,最好将它们存储在数组中,只需在需要时设置隐藏属性即可。

标题中的

    NSMutableArray* coins;

在m文件中:

-(void)newCoin;
{
    //create the array if it doesn't already exist - could add this to your init
    if(!coins)
    {
        coins = [NSMutableArray array];
    }
    for(CALayer* aCoin in coins)
    {
        //find the first hidden coin and use it
        if(aCoin.hidden)
        {
            //reset the coins position to where you want the "new" coin
            return;
        }
    }
    //didn't find any unused coins - make a new one
    [coins addObject:[self createCoin]];

当动画完成时,只需将硬币的隐藏属性设置为真。

coin.hidden = YES;

我使用这种方法一次处理数千个CALayer对象,它比不断创建新的CALayer更加资源友好。