Fade In Fade Out Animation

后端 未结 13 1269
生来不讨喜
生来不讨喜 2021-01-30 01:45

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

13条回答
  •  误落风尘
    2021-01-30 01:56

    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.

提交回复
热议问题