iOS之常用第三方库的实用

iOS开发之MBProgressHUD

2016-03-12  本文已影响2639人  邦奇诺

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是一款优化用户体验绝佳的第三方工具! **

上一篇下一篇

猜你喜欢

热点阅读