MBProgressHUD学习笔记

作者: DylanPP | 来源:发表于2017-07-20 14:07 被阅读28次

    MBProgressHUD是一个 UI 层面的第三方框架, 它的使用方便快捷,而且只有两个文件,一个头文件和一个实现文件,很适合作为阅读学习源码的第一道菜。
    MBProgressHUD是 UIView 的子类, 它提供了一系列的创建 HUD 的方法,我们可以从以下三个方面实现来了解并学习MBProgressHUD

    • API
    • 方法调用
    • 方法内部实现

    API

    关键属性

      @property (assign, nonatomic) MBProgressHUDMode mode;//类型
      @property (assign, nonatomic) MBProgressHUDAnimation animationType;//动画类型
      @property (assign, nonatomic) NSTimeInterval graceTime;//show函数触发到显示HUD的时间段
      @property (assign, nonatomic) NSTimeInterval minShowTime;//HUD显示的最短时间
    

    方法调用

    • 类方法
      /**
      * 在某个view上添加HUD并显示
      *
      * 注意:显示之前,先去掉在当前view上显示的HUD。这个做法很严谨,我们将这个方案抽象出来:如果一个模型是这样的:我们需要将A加入到B中,但是需求上B里面只允许只有一个A。那么每次将A添加到B之前,都要先判断当前的b里面是否有A,如果有,则移除。
      /
      + (instancetype)showHUDAddedTo:(UIView )view animated:(BOOL)animated;
      /

      * 找到某个view上最上层的HUD并隐藏它。
      * 如果返回值是YES的话,就表明HUD被找到而且被移除了。
      /
      + (BOOL)hideHUDForView:(UIView )view animated:
      (BOOL)animated;
      /

      * 在某个view上找到最上层的HUD并返回它。
      * 返回值可以是空,所以返回值的关键字为:nullable
      */
      + (nullable MBProgressHUD *)HUDForView:(UIView *)view;
    • 对象方法:
      /**
      * 一个HUD的便利构造函数,用某个view来初始化HUD:这个view的bounds就是HUD的bounds
      /
      - (instancetype)initWithView:(UIView )view;
      /

      * 显示HUD,有无动画。
      /
      - (void)showAnimated:(BOOL)animated;
      /
      *
      * 隐藏HUD,有无动画。
      /
      - (void)hideAnimated:(BOOL)animated;
      /
      *
      * 在delay的时间过后隐藏HUD,有无动画。
      */
      - (void)hideAnimated:(BOOL)animated afterDelay:(NSTimeInterval)delay;

    方法内部实现

    • show:在初始化一个 HUD 并添加到 view 上之后, 这时 HUD 并没有显示出来, 因为在初始化时, view.alpha 被设置为 0. 所以我们接下来会调用 - show: 方法使 HUD 显示到屏幕上。
    + (instancetype)showHUDAddedTo:(UIView *)view animated:(BOOL)animated {
        MBProgressHUD *hud = [[self alloc] initWithView:view];// 接着调用 [self initWithFrame:view.bounds]:根据传进来的view的frame来设定自己的frame
        hud.removeFromSuperViewOnHide = YES;//removeFromSuperViewOnHide 应该是一个标记,表明HUD自己处于“应该被移除的状态”
        [view addSubview:hud];//在view上将自己的实例添加上去
        [hud showAnimated:animated];
        return hud;
    }
    //调用showAnimated:
    - (void)showAnimated:(BOOL)animated {
        MBMainThreadAssert();
        [self.minShowTimer invalidate];//取消当前的minShowTimer
         self.useAnimation = animated;//设置animated状态
         self.finished = NO;//添加标记:表明当前任务仍在进行
        // 如果设定了graceTime,就要推迟HUD的显示
        if (self.graceTime > 0.0) {
            NSTimer *timer = [NSTimer timerWithTimeInterval:self.graceTime target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
            [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
            self.graceTimer = timer;
        } 
        // ... otherwise show the HUD immediately
        else {
            [self showUsingAnimation:self.useAnimation];
        }
    }
    //self.graceTimer触发的方法
    - (void)handleGraceTimer:(NSTimer *)theTimer {
        // Show the HUD only if the task is still running
        if (!self.hasFinished) {
            [self showUsingAnimation:self.useAnimation];
        }
    }
    //所有的show方法最终都会走到这个方法
    - (void)showUsingAnimation:(BOOL)animated {
        // Cancel any previous animations
        [self.bezelView.layer removeAllAnimations];
        [self.backgroundView.layer removeAllAnimations];
    
        // Cancel any scheduled hideDelayed: calls
        [self.hideDelayTimer invalidate];
    
        self.showStarted = [NSDate date];
        self.alpha = 1.f;
    
        // Needed in case we hide and re-show with the same NSProgress object attached.
        [self setNSProgressDisplayLinkEnabled:YES];
    
        if (animated) {
            [self animateIn:YES withType:self.animationType completion:NULL];
        } else {
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wdeprecated-declarations"
            self.bezelView.alpha = self.opacity;
    #pragma clang diagnostic pop
            self.backgroundView.alpha = 1.f;
        }
    }
    
    

    如果 graceTime 为 0 那么直接调用- showUsingAnimation:方法, 否则会创建一个 newGraceTimer 当然这个 timer 对应的 selector 最终调用的也是- showUsingAnimation:方法。
    它在方法刚调用时会通过-cancelPreviousPerformRequestsWithTarget: 移除附加在 HUD 上的所有 selector, 这样可以保证该方法不会多次调用.
    同时也会保存 HUD 的出现时间.

    self.showStarted = [NSDate date]
    

    **HUD **动画类型

    typedef NS_ENUM(NSInteger, MBProgressHUDAnimation) {
        /** Opacity animation */
        MBProgressHUDAnimationFade,
        /** Opacity + scale animation */
        MBProgressHUDAnimationZoom,
        MBProgressHUDAnimationZoomOut = MBProgressHUDAnimationZoom,
        MBProgressHUDAnimationZoomIn
    };
    
    • hide+ hideHUDForView:animated:方法的实现和 + showHUDAddedTo:animated:差不多, + HUDForView:方法会返回对应 view 最上层的 MBProgressHUD 的实例.然后调用的 - hide:方法并最终执行- hideUsingAnimation:方法,且在 HUD 隐藏之后 - done 负责隐藏执行 completionBlockdelegate 回调.
    + (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated {
        MBProgressHUD *hud = [self HUDForView:view];//获取当前view的最前为止的HUD
        if (hud != nil) {
            hud.removeFromSuperViewOnHide = YES;
            [hud hideAnimated:animated];
            return YES;
        }
        return NO;
    }
    + (MBProgressHUD *)HUDForView:(UIView *)view {   
        NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator]; //倒叙排序
        for (UIView *subview in subviewsEnum) {
            if ([subview isKindOfClass:self]) {
                return (MBProgressHUD *)subview;
            }
        }
        return nil;
    }
    - (void)hideAnimated:(BOOL)animated {
        MBMainThreadAssert();
        [self.graceTimer invalidate];
         self.useAnimation = animated;
         self.finished = YES;
         //如果设定了HUD最小显示时间,那就需要判断最小显示时间和已经经过的时间的大小
         if (self.minShowTime > 0.0 && self.showStarted) {
            NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:self.showStarted];
            
            //如果最小显示时间比较大,则暂时不触发HUD的隐藏,而是启动一个timer,再经过二者的时间差的时间之后再触发隐藏
            if (interv < self.minShowTime) {
                NSTimer *timer = [NSTimer timerWithTimeInterval:(self.minShowTime - interv) target:self selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO];
                [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
                self.minShowTimer = timer;
                return;
            } 
         }
        //如果最小显示时间比较小,则立即将HUD隐藏
        [self hideUsingAnimation:self.useAnimation];
    }
    //self.minShowTimer触发的方法
    - (void)handleMinShowTimer:(NSTimer *)theTimer {
        [self hideUsingAnimation:self.useAnimation];
    }
    - (void)hideUsingAnimation:(BOOL)animated {
        if (animated && self.showStarted) {
            //隐藏时,将showStarted设为nil
            self.showStarted = nil;
            [self animateIn:NO withType:self.animationType completion:^(BOOL finished) {
                [self done];
            }];
        } else {
            self.showStarted = nil;
            self.bezelView.alpha = 0.f;
            self.backgroundView.alpha = 1.f;
            [self done];
        }
    }
    

    测试Demo

    - (void)MBProgressHUD
    {
        /*
        1,创建对象,2,将HUD添加到view上,3,调用show方法隐藏;
        1,hide:方法, 2,hide: afterDelay: 
         */
        HUD = [[MBProgressHUD alloc] init];
        [self.view addSubview:HUD];
    //    HUD.mode = MBProgressHUDModeIndeterminate;//菊花,默认值
    //    HUD.mode = MBProgressHUDModeDeterminate;//圆饼,饼状图
    //    HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;//进度条
        HUD.mode = MBProgressHUDModeAnnularDeterminate;//圆环作为进度条
    //    HUD.mode = MBProgressHUDModeCustomView; //需要设置自定义视图时候设置成这个
    //    HUD.mode = MBProgressHUDModeText; //只显示文本
    
        //1,设置背景框的透明度  默认0.8
        HUD.opacity = 1;
        //2,设置背景框的背景颜色和透明度, 设置背景颜色之后opacity属性的设置将会失效
        HUD.color = [UIColor redColor];
        HUD.color = [HUD.color colorWithAlphaComponent:1];
        //3,设置背景框的圆角值,默认是10
        HUD.cornerRadius = 20.0;
        //4,设置提示信息 信息颜色,字体
        HUD.labelColor = [UIColor blueColor];
        HUD.labelFont = [UIFont systemFontOfSize:13];
        HUD.labelText = @"Loading...";
        //5,设置提示信息详情 详情颜色,字体
        HUD.detailsLabelColor = [UIColor blueColor];
        HUD.detailsLabelFont = [UIFont systemFontOfSize:13];
        HUD.detailsLabelText = @"LoadingLoading...";
        //6,设置菊花颜色  只能设置菊花的颜色
        HUD.activityIndicatorColor = [UIColor blackColor];
        //7,设置一个渐变层
        HUD.dimBackground = YES;
        //8,设置动画的模式
    //    HUD.mode = MBProgressHUDModeIndeterminate;
        //9,设置提示框的相对于父视图中心点的便宜,正值 向右下偏移,负值左上
        HUD.xOffset = -80;
        HUD.yOffset = -100;
        //10,设置各个元素距离矩形边框的距离
        HUD.margin = 0;
        //11,背景框的最小大小
        HUD.minSize = CGSizeMake(50, 50);
        //12设置背景框的实际大小   readonly
        CGSize size = HUD.size;
        //13,是否强制背景框宽高相等
        HUD.square = YES;
        //14,设置显示和隐藏动画类型  有三种动画效果,如下
    //    HUD.animationType = MBProgressHUDAnimationFade; //默认类型的,渐变
    //    HUD.animationType = MBProgressHUDAnimationZoomOut; //HUD的整个view后退 然后逐渐的后退
        HUD.animationType = MBProgressHUDAnimationZoomIn; //和上一个相反,前近,最后淡化消失
        //15,设置最短显示时间,为了避免显示后立刻被隐藏   默认是0
    //    HUD.minShowTime = 10;
        //16,
        /*
         // 这个属性设置了一个宽限期,它是在没有显示HUD窗口前被调用方法可能运行的时间。
         // 如果被调用方法在宽限期内执行完,则HUD不会被显示。
         // 这主要是为了避免在执行很短的任务时,去显示一个HUD窗口。
         // 默认值是0。只有当任务状态是已知时,才支持宽限期。具体我们看实现代码。
         @property (assign) float graceTime;
    
         // 这是一个标识位,标明执行的操作正在处理中。这个属性是配合graceTime使用的。
         // 如果没有设置graceTime,则这个标识是没有太大意义的。在使用showWhileExecuting:onTarget:withObject:animated:方法时,
         // 会自动去设置这个属性为YES,其它情况下都需要我们自己手动设置。
         @property (assign) BOOL taskInProgress;
         */
        //17,设置隐藏的时候是否从父视图中移除,默认是NO
        HUD.removeFromSuperViewOnHide = NO;
        //18,进度指示器  模式是0,取值从0.0————1.0
    //    HUD.progress = 0.5;
        //19,隐藏时候的回调 隐藏动画结束之后
        HUD.completionBlock = ^(){
            NSLog(@"abnnfsfsf");
        };
        //设置任务,在hud上显示任务的进度
        [HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
    
    //    [HUD show:YES];
    
        //两种隐藏的方法
    //    [HUD hide:YES];
        [HUD hide:YES afterDelay:5];
    }
    

    进度Demo

    - (void)ProgressTask :(NetLoad *)loading{
            HUD.progress = loading;
    }
    
    

    网络访问请求:中文空格字符编码/解码

    NSString *str1 = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    

    好记性不如烂笔头。

    END

    微博@迪达拉君
    GithubZhaoBinLe

    相关文章

      网友评论

        本文标题:MBProgressHUD学习笔记

        本文链接:https://www.haomeiwen.com/subject/gvidkxtx.html