Fadein / out text animation
I am using an NSTimer (5 seconds duration) with a selector to select a random name from an NSArray.
Here is some code
....
NSDate *endtime = [NSDate dateWithTimeIntervalSinceNow:5];
[NSTimer scheduledTimerWithTimeInterval:0.2
target:self
selector:@selector(selectPlayer:)
userInfo:endtime
repeats:YES ];
...
-(void)selectPlayer:(NSTimer *)timer
{
if ([timer.userInfo timeIntervalSinceNow] < 0)
{
[timer invalidate];
}
NSString *playerName = [[NSString alloc]initWithFormat:@"%@",
[self.playersNames objectAtIndex:random() & [self.playersNames count]-1]];
self.playersLabel.text = playerName;
[playerName release];
}
This code works efficiently. self.playersLabel is filled with a random name every 0.2 seconds.
I want to add a fadein / fadeout animation effect while the names are changed in playersLabel.
How to do it?
source to share
You just need to add animation when you change the text playersLabel
Here's how you can do it:
[UIView animateWithDuration:0.1 delay:0.f options:UIViewAnimationOptionCurveEaseInOut
animations:^{
playersLabel.alpha = 0.f;
} completion:^(BOOL complete){
[UIView animateWithDuration:0.1 delay:0.f options:UIViewAnimationOptionCurveEaseInOut
animations:^{
playersLabel.text = playerName;
playersLabel.alpha = 1.f;
} completion:NULL];
}];
I used the first animation completion block to reset back the alpha value of the label. Each animation lasts 0.1 because yours playerName
is picked every 0.2 seconds (0.1 * 2). You could use UIViewAnimationOptionAutoreverse
, but if I remember it doesn't reset the alpha property of the label.
source to share