ios MBProgressHUD 使用,及二次封裝


MBProgressHUD是一個顯示HUD窗口的第三方類庫,用於在執行一些后台任務時,在程序中顯示一個表示進度的loading視圖和兩個可選的文本提示的HUD窗口。MBProgressHUD 二次封裝網上有很多教程,大多數我們在 MVC 模式下發送網絡大多都在 UIVIewCOntroller 進行,需要使用彈窗的地方大多也都在controller 中,所有之前給 UIViewCOntroller 寫了個分類,方便調用,但是后來覺得在基類中使用不太好,所以今天重新整理一下. demo 地址:https://github.com/SummerHH/YJMBProgressHUD.git

先了解下 MBProgressHUD 使用:

HUD窗口的模式:

// 使用UIActivityIndicatorView來顯示進度,這是默認值
MBProgressHUDModeIndeterminate,
// 使用一個圓形餅圖來作為進度視圖
MBProgressHUDModeDeterminate,
// 使用一個水平進度條
MBProgressHUDModeDeterminateHorizontalBar,
// 使用圓環作為進度條
MBProgressHUDModeAnnularDeterminate,
// 顯示一個自定義視圖,通過這種方式,可以顯示一個正確或錯誤的提示圖
MBProgressHUDModeCustomView,
// 只顯示文本
MBProgressHUDModeText

一個MBProgressHUD視圖主要由四個部分組成:

1.標題文本

@property (strong, nonatomic, readonly) UILabel *label;

2.詳情文本

@property (strong, nonatomic, readonly) UILabel *detailsLabel;

3.loading動畫視圖

@property (strong, nonatomic, nullable) UIView *customView;

4.HUD背景框

@property (strong, nonatomic, readonly) MBBackgroundView *bezelView;

 

 

外觀屬性:

設置顏色 默認為半半透明的黑色和白色的iOS 7和早iOS版本

@property (strong, nonatomic, nullable) UIColor *contentColor UI_APPEARANCE_SELECTOR;

//設置顯示大小

@property (assign, nonatomic) CGSize minSize UI_APPEARANCE_SELECTOR;

//隱藏后從父視圖中移除

@property (assign, nonatomic) BOOL removeFromSuperViewOnHide;

 

//是否顯示蒙版,不過1.0.0版本被棄用了
@property (assign) BOOL dimBackground;

- (void)drawRect:(CGRect)rect {

 

    ...

 

    if (self.dimBackground) {

        //Gradient colours

        size_t gradLocationsNum = 2;

        CGFloat gradLocations[2] = {0.0f, 1.0f};

        CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f}; 

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);

        CGColorSpaceRelease(colorSpace);

 

        //Gradient center

        CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);

        //Gradient radius

        float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;

 

        // 由中心向四周繪制漸變

        CGContextDrawRadialGradient (context, gradient, gradCenter,

                                     0, gradCenter, gradRadius,

                                     kCGGradientDrawsAfterEndLocation);

        CGGradientRelease(gradient);

    }

    ... 

}

 

 

//創建布局

- (id)initWithView:(UIView *)view;

 

控制布局的屬性

// HUD相對於父視圖中心點的x軸偏移量和y軸偏移量

@property (assign) float xOffset;

@property (assign) float yOffset;

 

// HUD各元素與HUD邊緣的間距

@property (assign) float margin;

 

// HUD背景框的最小大小

@property (assign) CGSize minSize;

 

// HUD的實際大小

@property (atomic, assign, readonly) CGSize size;

 

// 是否強制HUD背景框寬高相等

@property (assign, getter = isSquare) BOOL square;

//顯示和隱藏的方法

- (void)showAnimated:(BOOL)animated;
- (void)hideAnimated:(BOOL)animated;

 

經常在 UIViewController 中使用,可以給 UIVIewController 寫個分類

使用簡單方便

#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
@interface UIViewController (HUD)
-(void)showSuccess:(NSString *)success;
-(void)showError:(NSString *)error;
-(void)showMessage:(NSString *)message;
-(void)showWaiting;
-(void)showLoading;
-(void)showLoadingWithMessage:(NSString *)message;
-(void)showSaving;
-(void)hideHUD;
@end
@implementation UIViewController (HUD)
-(void)showSuccess:(NSString *)success
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.contentColor=[UIColor whiteColor];
    HUD.bezelView.color=[UIColor blackColor];
    HUD.mode=MBProgressHUDModeText;
    HUD.label.text=success;
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
    [HUD hideAnimated:YES afterDelay:1];
}
-(void)showError:(NSString *)error
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.contentColor=[UIColor whiteColor];
    HUD.bezelView.color=[UIColor blackColor];
    HUD.mode=MBProgressHUDModeText;
    HUD.label.text=error;
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
    [HUD hideAnimated:YES afterDelay:1];
}
-(void)showMessage:(NSString *)message
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.contentColor=[UIColor whiteColor];
    HUD.bezelView.color=[UIColor blackColor];
    HUD.mode=MBProgressHUDModeText;
    HUD.label.text=message;
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
    [HUD hideAnimated:YES afterDelay:1];
}
-(void)showWaiting
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    HUD.bezelView.color = [UIColor blackColor];
    HUD.contentColor=[UIColor whiteColor];
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
}
-(void)showLoading
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    HUD.bezelView.color = [UIColor blackColor];
    HUD.contentColor=[UIColor whiteColor];
    HUD.label.text=@"正在加載";
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
}
-(void)showLoadingWithMessage:(NSString *)message
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    HUD.bezelView.color = [UIColor blackColor];
    HUD.contentColor=[UIColor whiteColor];
    HUD.label.text=message;
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
}
-(void)showSaving
{
    MBProgressHUD *HUD=[[MBProgressHUD alloc]initWithView:[self getView]];
    HUD.backgroundView.color = [UIColor colorWithWhite:0.f alpha:.2f];
    HUD.bezelView.color = [UIColor blackColor];
    HUD.contentColor=[UIColor whiteColor];
    HUD.label.text=@"正在保存";
    HUD.removeFromSuperViewOnHide=YES;
    [[self getView] addSubview:HUD];
    [HUD showAnimated:YES];
}
-(void)hideHUD
{
    [MBProgressHUD hideHUDForView:[self getView] animated:YES];
}
-(UIView *)getView
{
    UIView *view;
    if (self.navigationController.view) {
        view=self.navigationController.view;
    }else
    {
        view=self.view;
    }
    return view;
}

另一種可以配合網絡使用,也可以 用在 Controller中

#import <MBProgressHUD/MBProgressHUD.h>

typedef NS_ENUM(NSInteger, YJProgressHUDStatus) {
    
    /** 成功 */
    YJProgressHUDStatusSuccess,
    
    /** 失敗 */
    YJProgressHUDStatusError,
    
    /** 警告*/
    YJProgressHUDStatusWaitting,
    
    /** 提示 */
    YJProgressHUDStatusInfo,
    
    /** 等待 */
    YJProgressHUDStatusLoading

};

@interface YJProgressHUD : MBProgressHUD

/**
 *  是否正在顯示
 */
@property (nonatomic, assign, getter=isShowNow) BOOL showNow;

/** 返回一個 HUD 的單例 */
+ (instancetype)sharedHUD;

/** 在 window 上添加一個 HUD */
+ (void)showStatus:(YJProgressHUDStatus)status text:(NSString *)text;



#pragma mark - 建議使用的方法

/** 在 window 上添加一個只顯示文字的 HUD */
+ (void)showMessage:(NSString *)text;

/** 在 window 上添加一個提示`信息`的 HUD */
+ (void)showWaiting:(NSString *)text;

/** 在 window 上添加一個提示`失敗`的 HUD */
+ (void)showError:(NSString *)text;

/** 在 window 上添加一個提示`成功`的 HUD */
+ (void)showSuccess:(NSString *)text;

/** 在 window 上添加一個提示`等待`的 HUD, 需要手動關閉 */
+ (void)showLoading:(NSString *)text;

/** 手動隱藏 HUD */
+ (void)hideHUD;
#import "YJProgressHUD.h"

// 背景視圖的寬度/高度
#define BGVIEW_WIDTH 100.0f
// 文字大小
#define TEXT_SIZE    16.0f

@implementation YJProgressHUD

+ (instancetype)sharedHUD {
    static id hud;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hud = [[self alloc] initWithView:[UIApplication sharedApplication].keyWindow];
    });
    return hud;
}

+ (void)showStatus:(YJProgressHUDStatus)status text:(NSString *)text {
    
    YJProgressHUD *HUD = [YJProgressHUD sharedHUD];
    HUD.bezelView.color = [UIColor colorWithHex:0x000000];
    HUD.contentColor=[UIColor whiteColor];
    [HUD showAnimated:YES];
    [HUD setShowNow:YES];
    //蒙版顯示 YES , NO 不顯示
//        HUD.dimBackground = YES;
    HUD.label.text = text;
    HUD.label.textColor = [UIColor whiteColor];
    [HUD setRemoveFromSuperViewOnHide:YES];
    HUD.label.font = [UIFont boldSystemFontOfSize:TEXT_SIZE];
    [HUD setMinSize:CGSizeMake(BGVIEW_WIDTH, BGVIEW_WIDTH)];
    [[UIApplication sharedApplication].keyWindow addSubview:HUD];
    
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"YJProgressHUD" ofType:@"bundle"];
    
    switch (status) {
            
        case YJProgressHUDStatusSuccess: {
            
            NSString *sucPath = [bundlePath stringByAppendingPathComponent:@"MBHUD_Success.png"];
            UIImage *sucImage = [UIImage imageWithContentsOfFile:sucPath];
            
            HUD.mode = MBProgressHUDModeCustomView;
            UIImageView *sucView = [[UIImageView alloc] initWithImage:sucImage];
            HUD.customView = sucView;
            [HUD hideAnimated:YES afterDelay:2.0f];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [HUD setShowNow:NO];
            });
        }
            break;
            
        case YJProgressHUDStatusError: {
            
            NSString *errPath = [bundlePath stringByAppendingPathComponent:@"MBHUD_Error.png"];
            UIImage *errImage = [UIImage imageWithContentsOfFile:errPath];
            
            HUD.mode = MBProgressHUDModeCustomView;
            UIImageView *errView = [[UIImageView alloc] initWithImage:errImage];
            HUD.customView = errView;
            [HUD hideAnimated:YES afterDelay:2.0f];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [HUD setShowNow:NO];
            });
        }
            break;
            
        case YJProgressHUDStatusLoading: {
            HUD.mode = MBProgressHUDModeIndeterminate;
        }
            break;
            
            
        case YJProgressHUDStatusWaitting: {
            NSString *infoPath = [bundlePath stringByAppendingPathComponent:@"MBHUD_Warn.png"];
            UIImage *infoImage = [UIImage imageWithContentsOfFile:infoPath];
            
            HUD.mode = MBProgressHUDModeCustomView;
            UIImageView *infoView = [[UIImageView alloc] initWithImage:infoImage];
            HUD.customView = infoView;
            [HUD hideAnimated:YES afterDelay:2.0f];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [HUD setShowNow:NO];
            });

        }
            break;
            
        case YJProgressHUDStatusInfo: {
            
            NSString *infoPath = [bundlePath stringByAppendingPathComponent:@"MBHUD_Info.png"];
            UIImage *infoImage = [UIImage imageWithContentsOfFile:infoPath];
            
            HUD.mode = MBProgressHUDModeCustomView;
            UIImageView *infoView = [[UIImageView alloc] initWithImage:infoImage];
            HUD.customView = infoView;
            [HUD hideAnimated:YES afterDelay:2.0f];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [HUD setShowNow:NO];
            });
        }
            break;
            
        default:
            break;
    }
}

+ (void)showMessage:(NSString *)text {
    
    YJProgressHUD *HUD = [YJProgressHUD sharedHUD];
    HUD.bezelView.color = [UIColor colorWithHex:0x000000];
    [HUD showAnimated:YES];
    [HUD setShowNow:YES];
    HUD.label.text = text;
    HUD.contentColor=[UIColor whiteColor];
    [HUD setMinSize:CGSizeZero];
    [HUD setMode:MBProgressHUDModeText];
    //    HUD.dimBackground = YES;
    [HUD setRemoveFromSuperViewOnHide:YES];
    HUD.label.font = [UIFont boldSystemFontOfSize:TEXT_SIZE];
    [[UIApplication sharedApplication].keyWindow addSubview:HUD];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[YJProgressHUD sharedHUD] setShowNow:NO];
        [[YJProgressHUD sharedHUD] hideAnimated:YES];
    });
}

+ (void)showWaiting:(NSString *)text {
    
    [self showStatus:YJProgressHUDStatusWaitting text:text];
}

+ (void)showError:(NSString *)text {
    
    [self showStatus:YJProgressHUDStatusError text:text];
}

+ (void)showSuccess:(NSString *)text {
    
    [self showStatus:YJProgressHUDStatusSuccess text:text];
}

+ (void)showLoading:(NSString *)text {
    
    [self showStatus:YJProgressHUDStatusLoading text:text];
}

+ (void)hideHUD {
    
    [[YJProgressHUD sharedHUD] setShowNow:NO];
    [[YJProgressHUD sharedHUD] hideAnimated:YES];
}

效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM