iOS開發之MBProgressHUD

MBProgressHUD是一款第三方工具,用來增加 App 的用戶體驗,俗稱小菊花。

1、MBProgressHUD簡介

很多時候,我們進入頁面的時候,因為程序正在讀取數據,頁面呈現出一片空白。這會引起用戶的焦慮,造成不好的用戶體驗。這個時候,如果能用一個過渡,便會緩解這種狀況。
MBProgressHUD就是為了滿足這種需求開發出來的第三方工具,使用 MBProgressHUD 在空白期出現一個轉動的小菊花,用來過濾。
效果如下:

MBprogressHUD示例

2、MBProgressHUD的簡單使用

我們現在模擬這樣一個場景來進行對 MBProgressHUD 的講解:

通過點擊一個 Button 然后等待加載一個 ImageView

** 代碼如下: **
第一步:RootViewController.h 文件:

#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"

@interface RootViewController : UIViewController

//  1. 創建按鈕
@property(nonatomic, strong) UIButton *aButton;
//  2. 創建顯示視圖
@property(nonatomic, strong) UIView *aView;
//  3. 創建加載視圖
@property(nonatomic, strong) MBProgressHUD *aProgressHUD;

@end

第二步:RootViewController.m 文件:
1、在 viewDidLoad 方法中對以上空間進行初始化:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //  1. 設置 Root 背景色
    self.view.backgroundColor = [UIColor whiteColor];
    
    //  2. 設置 aButton
    _aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _aButton.frame = CGRectMake(157, 650, 100, 30);
    _aButton.backgroundColor = [UIColor brownColor];
    [_aButton setTitle:@"加載圖片" forState: UIControlStateNormal];
    [self.view addSubview:_aButton];
    
    //  * 添加 aButton 事件
    [_aButton addTarget:self action:@selector(buttonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    //  3. 設置 aView
    _aView = [[UIView alloc] initWithFrame:CGRectMake(0, 75, 414, 550)];
    _aView.backgroundColor = [UIColor brownColor];
    [self.view addSubview:_aView];
    
    //  4. 設置 aProgressHUD
    _aProgressHUD = [MBProgressHUD new];
    _aProgressHUD.labelText = @"加載中...";
    _aProgressHUD.mode = MBProgressHUDModeAnnularDeterminate;
    [self.view addSubview:_aProgressHUD];
}

2、創建 aButton 事件方法:

- (void)buttonDidClicked:(UIButton *)sender {
    //  1. 彈出 aProgressHUD
    [_aProgressHUD showAnimated:YES whileExecutingBlock:^{
        //  2. 彈出延遲 (單位: 秒)
        sleep(1);
        //  3. 設置進度條變化 (aProgressHUD.progress 為進度條百分比, 其值 (0.0 - 1.0))
        while (_aProgressHUD.progress < 1.0) {
            _aProgressHUD.progress += 0.02;
            //  4. 設置變化延遲 (單位: 微妙)
            usleep(20000);
        }
        //  5. 設置進度條走完之后的事件
    } completionBlock:^{
        //  6. aBUtton 文字改變
        _aButton.titleLabel.text = @"加載完成";
        //  7. aVIew 背景改變
        _aView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"image.jpg"]];
        //  8. 移除 aProgessHUD
        [_aProgressHUD removeFromSuperview];
    }];
}

加載完畢之后,就會出現這張圖片:


加載完畢

** 總之,MBProgressHUD是一款優化用戶體驗絕佳的第三方工具! **

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容