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 ou
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
#import
@interface UIView (Animations)
- (void)fadeInWithCompletion:(void (^ __nullable)(BOOL finished))completion;
- (void)fadeOutWithCompletion:(void (^ __nullable)(BOOL finished))completion;;
@end
UIView+Animations.m
#import "UIView+Animations.h"
@implementation UIView (Animations)
- (void)fadeInWithCompletion:(void (^ __nullable)(BOOL finished))completion {
[UIView animateWithDuration:2 animations:^{
[self setAlpha:1];
} completion:completion];
}
- (void)fadeOutWithCompletion:(void (^ __nullable)(BOOL finished))completion {
[UIView animateWithDuration:2 animations:^{
[self setAlpha:0];
} completion:completion];
}
@end
So, you only have to import the new file to your class or inside your Prefix.pch
and use it like this:
[_label fadeOutWithCompletion:^(BOOL finished) {
[_label fadeInWithCompletion:nil];
}];
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 from UIView
.