Here is some code I struggle with for a while.
If you start the fade in animation, the label text fades in. If I start the fade out animation the the label text fades out.
When I start the startFade
method, only fade out is shown. How can I wait for the fadeIn
method to finish visually before starting the fadeOut
method.
-(IBAction)startFade:(id)sender{
[self fadeIn];
[self fadeOut];
}
-(IBAction)fadeIn:(id)sender{
[self fadeIn];
}
-(IBAction)fadeOut:(id)sender{
[self fadeOut];
}
-(void) fadeIn{
[_label setAlpha:0];
[UILabel beginAnimations:NULL context:nil];
[UILabel setAnimationDuration:2.0];
[_label setAlpha:1];
[UILabel commitAnimations];
}
-(void) fadeOut{
[UILabel beginAnimations:NULL context:nil];
[UILabel setAnimationDuration:2.0];
[_label setAlpha:0];
[UILabel commitAnimations];
}
When you call the
fadeIn
andfadeOut
methods back to back like you're doing, the code is run instantaneously, so you'll only see animation from the last method called. UIView block based animation provides a completion handler, which seems to be exactly what you're looking for. So your code might looks something like this:Swift:
Based on @holex's answer, but simplified a bit (as commented):
I strongly suggest you use a generic implementation so you can reuse the code whenever you need the fade effect again.
You should create an
UIView
extension:UIView+Animations.h
UIView+Animations.m
So, you only have to import the new file to your class or inside your
Prefix.pch
and use it like this:Note that you could also use
nil
as the completion parameter when you have nothing else to do after completion.I also recommend you do not parameterize the duration to keep a pattern through you entire application.
This implementation can be used in the future for
UIButton
,UILabel
,UITextField
... Well, any class derived fromUIView
.My task was to make a label fade out. And then fade in with changed text. The solution was:
that does the job for you (the
_label
is your label);