重叠动画有帮助吗?

时间:2009-09-26 20:32:40

标签: iphone cocoa-touch animation uiimageview

这是我的代码,用于使蝙蝠拍打翅膀并对触摸做出反应。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSArray * imageArray = [[NSArray alloc] initWithObjects:
                            [UIImage imageNamed:@"Bat1.png"],
                            [UIImage imageNamed:@"Bat2.png"],
                            [UIImage imageNamed:@"Bat3.png"],
                            [UIImage imageNamed:@"Bat2.png"],
                            [UIImage imageNamed:@"Bat1.png"],
                            [UIImage imageNamed:@"Bat4.png"], 
                            [UIImage imageNamed:@"Bat5.png"],
                            [UIImage imageNamed:@"Bat6.png"],
                            [UIImage imageNamed:@"Bat5.png"],
                            [UIImage imageNamed:@"Bat4.png"],
                            nil];

    UIImageView * batView = [[UIImageView alloc] initWithFrame:
                             CGRectMake(0, 0, 80, 56)];
    batView.animationImages = imageArray;
    batView.animationDuration = 0.70;
    [follower1 addSubview:batView];
    [batView startAnimating];
    [UIImageView beginAnimations:@"follow" context:nil];
    [UIImageView setAnimationDuration:1];
    [UIImageView setAnimationBeginsFromCurrentState:YES];
    UITouch *touch = [touches anyObject];
    follower1.center = [touch locationInView:self];
    [UIImageView commitAnimations];
    [batView release]; 
}

问题是,在第二次触摸后,动画重叠在一起,所以每次触摸后看起来下面都有很多蝙蝠!

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为每次触摸开始时您都会添加新的batView

解决此问题的一种方法是添加batView一次,例如在superview或视图控制器的init方法中。如果您只想在触摸发生时显示batView,则可以通过以下方式隐藏它:

// during initialization
batView.hidden = YES;

由于您每次都在进行相同的动画,因此您也可以同时设置动画参数,而不是每次触摸都重复相同的设置:

// still during initialization
NSArray* imageArray = /* set up your image array */;
batView.animationImages = imageArray;
batView.animationDuration = 0.7;

现在,当触摸发生时,您可以通过启动动画来处理它:

// Within touchesBegan:
    ...
    // Start the batView animation.
    batView.hidden = NO;
    if (![batView isAnimating]) [batView startAnimating];
    // Hide the animation when it's done.
    [self performSelector:@selector(hideBat) withObject:nil afterDelay:0.71];
}

// Later:

- (void) hideBat { batView.hidden = YES; }

如果您不希望在单个动画后立即消失,则可能需要在hideBat中执行不同的操作。例如,如果您希望在用户停止点击之前始终重复动画,则可以设置NSTimer对象,以便在用户没有触摸至少0.7秒时立即关闭。每次用户再次触摸屏幕时,您都可以重置此计时器。

参考:UIImageView docs,其中包括动画方法的简要说明。