Reputation: 315
Right now I have an IBAction for a button which generates a random number with each number assigned to display text in a UILabel. Rather than just appear, I would like the text to fade in or any other interesting animation would be cool too. Does anyone know a simple way to make this happen?
Right now I just use
labelMain.text = @"my text";
Upvotes: 11
Views: 14664
Reputation: 2136
I know this is a bit stale (11 months old), but I think it's worth mentioning an alternative to the other approaches posted, which I feel is a better solution.
Make use of the UIView transitionWithView:duration:options:animations:completion
class-level method, like this:
NSTimeInterval duration = 0.5f;
[UIView transitionWithView:labelMain
duration:duration
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
labelMain.text = @"new value";
} completion:nil];
This will cross-fade from the previous value of labelMain.text
to "new value".
This approach works on other view values as well, such as changing the image of a UIImageView, for instance.
See Apple's docs on the topic.
Upvotes: 31
Reputation: 5268
This will look like cross fade animation
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut
animations:^{
labelMain.alpha = 0;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn
animations:^{ labelMain.alpha = 1;}
completion:nil];
} completion:nil];
Upvotes: 0
Reputation: 2919
The following code will give you fading effect on your label.
- (IBAction)buttonClicked:(UIButton *)sender
{
labelMain.alpha = 0;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn
animations:^{ labelMain.alpha = 1;}
completion:nil];
}
Upvotes: 27
Reputation: 21967
// fade out the current value
[UIView animateWithDuration:0.2
delay:0
options:0
animations:^{
labelMain.alpha = 0.0f;
}
completion:^(BOOL finished) {
// set the new value and fade in
labelMain.text = newValue;
[UIView animateWithDuration:0.2
delay:0
options:0
animations:^{
labelMain.alpha = 1.0f;
}
completion:nil];
}];
Upvotes: 0
Reputation: 1505
label.text = @"old text";
[UIView animateWithDuration:0.4 animations:^{
label.alpha = 0.0f;
} completion:^(BOOL finished) {
label.text = @"next text";
[UIView animateWithDuration:0.4 animations:^{
label.alpha = 1.0f;
} completion:^(BOOL finished) {
NSLog(@"finished transition");
}];
}];
Upvotes: 6
Reputation: 2941
Try this:
[labelMain setAlpha:0];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.8];
[labelMain setAlpha:1];
[UIView commitAnimations];
Changing the duration is pretty simple - just adjust the value 0.8
in the code.
Upvotes: 1