Objecive-C runtime实践-给Category添加属性

在开发中经常遇到需要添加hud的情形,每次添加的代码都在10行左右,遂新建一个ViewController的Category来添加hud。由于分类不能直接添加属性,就考虑到了runtime。
下面讲具体的实施步骤
新建工程--新建文件,选择Objective-C File 如下图:


Objecive-C runtime实践-给Category添加属性_第1张图片
屏幕快照 2016-01-19 21.43.58.png

导入MBProgressHUD, 现在项目结构如图:


Objecive-C runtime实践-给Category添加属性_第2张图片
屏幕快照 2016-01-19 21.48.11.png

在UIViewController+HUD.h中导入MBProgressHUD.h,

#import 
#import "MBProgressHUD.h"
@interface UIViewController (HUD)

@end

在UIViewController+HUD.m中导入runtime.h,并添加hud属性:

#import "UIViewController+HUD.h"
#import 

@interface UIViewController(Private)

@property (nonatomic, strong) MBProgressHUD *progressHud;

@end

@implementation UIViewController (HUD)
const char *kHudKey = "ProgressHUD_Key";


@end

接下来是关键的一步-设置hud的setter与getter方法:

- (void)setProgressHud:(MBProgressHUD *)progressHud
{
    objc_setAssociatedObject(self, kHudKey, progressHud, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (MBProgressHUD *)progressHud
{
    MBProgressHUD *hud = objc_getAssociatedObject(self, kHudKey);
    if (!hud) {
        UIView *view = self.navigationController.view;
        hud = [[MBProgressHUD alloc] initWithView:view];
        hud.removeFromSuperViewOnHide = YES;
        [view addSubview:hud];
        self.progressHud = hud;
    }
    return hud;
}

在setter中设置连接, 在getter中初始化。
好了,接下来就可以正常使用属性了,现在,我们对hud进行扩展。
写两个基本的show、hide方法,其余的实现在其基础上变化即可:

#pragma mark - Private
- (void)showHudWithMessage:(NSString *)message model:(MBProgressHUDMode)mode
{
    if (self.progressHud.taskInProgress) {
        return;
    }
    
    self.progressHud.taskInProgress = YES;
    self.progressHud.mode = mode ?: MBProgressHUDModeIndeterminate;
    self.progressHud.labelText = message;
    self.progressHud.labelFont = [UIFont systemFontOfSize:15];
    [self.progressHud show:YES];
    [self.progressHud hide:YES afterDelay:15];
}

- (void)hideHudWithMessage:(NSString *)message image:(UIImage *)image
{
    self.progressHud.customView = [[UIImageView alloc] initWithImage:image];
    self.progressHud.mode = MBProgressHUDModeCustomView;
    self.progressHud.labelText = message;
    self.progressHud.labelFont = [UIFont systemFontOfSize:15];
    
    [self.progressHud show:YES];
    [self performSelector:@selector(hideHud) withObject:nil afterDelay:0.7];
}

再实现下面的方法大概就够用了:

- (void)showHud;

- (void)showHudWithMessage:(NSString *)message;

- (void)showDeterminateHudWithMessage:(NSString *)message;

- (void)changeHudProgress:(double)precent;

- (void)hideHud;

- (void)hideHudWithSuccessMessage:(NSString *)message;

- (void)hideHudWithErrorMessage:(NSString *)message;

具体的实现直接看代码吧!
https://github.com/Xigtun/RuntimeDemo

你可能感兴趣的:(Objecive-C runtime实践-给Category添加属性)