Core Animation to flash score (UILabel)
I am using core animation to flash in开发者_开发知识库termediate scores (using UILabel) in a game on iPhone. I need it to repeat for certain count for a particular hit.
The score needs to be flashed for a particular count and then disappear. So it should go from alpha 0.0 -> 1.0 -> 0.0Below is the code with which I am trying to achieve this.
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationRepeatCount:repeatCount];
[UIView setAnimationRepeatAutoreverses:YES];
playerScore.alpha = 1.0f;
[UIView commitAnimations];
The problem is that after the animation is over, the alpha returns back to 1.0
Any suggestions?
I would use the more powerful animateWithDuration:delay:options:animations:completion:
method on UIView
. See View programming guide or UIView class reference
More specifically it could look like that: the method takes two blocks: one for the animation itself and one block which is execute once the animation is done. It maybe look a bit strange at first sight, but that is just the block syntax.
[UIView animateWithDuration:1.0 delay:0.f options:(UIViewAnimationOptionAutoreverse| UIViewAnimationOptionRepeat)
animations:^{
playerScore.alpha=1.f;
} completion:^(BOOL finished){
playerScore.alpha=0.f;
}];
This solution is for iOS version 4 or higher. If you want to target versions before that, you have to use a delegate callback. Set the selector to be executed when the animation is done like this:
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(flashingDidStop:finished:context:)];
//with the callback method
- (void)flashingDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
//code to execute in your case
playerScore.alpha = 0.f;
}
If you need this to work in iOS < 4.0 try this:
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
playerScore.alpha = 0.0f;
}
...
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView setAnimationDuration:1.0];
[UIView setAnimationRepeatCount:repeatCount];
[UIView setAnimationRepeatAutoreverses:YES];
playerScore.alpha = 1.0f;
[UIView commitAnimations];
精彩评论