iOS工具&效率&优化iOS DeveloperiOS开发

通过分类给控制器添加加载小菊花

2016-05-04  本文已影响139人  焚琴煮鹤de我
在分类中动态添加属性
#import "NSObject+Associate.h"
#import <objc/runtime.h>
@interface NSObject()
@property (nonatomic,strong)id object;
@end
@implementation NSObject (Associate)
static char const * objectKey;
+ (void)test{
    NSLog(@"test:%s",__func__);
}

- (void)setObject:(id)object{
    objc_setAssociatedObject(self, objectKey, object,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)object{
    return objc_getAssociatedObject(self, objectKey);
}
@end

知道这个后怎样用在自己的分类之中呢?

#import "UIViewController+Utils.h"
#import <objc/runtime.h>
const static char loadingViewKey;
@implementation UIViewController (Utils)


- (UIView *)loadingView {
  return objc_getAssociatedObject(self, &loadingViewKey);
}

- (void)setLoadingView:(UIView *)loadingView {
  objc_setAssociatedObject(self, &loadingViewKey, loadingView,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)showLoadingView {
  if (!self.loadingView) {
    UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc]
        initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.loadingView = loadingView;
    [self.view addSubview:self.loadingView];

   loadingView.center = CGPointMake(kScreenWidth / 2, (kScreenHeight - 20 - 44  * 2) / 2);
    [loadingView startAnimating];
  }
}

- (void)hideLoadingView {
  if (self.loadingView) {
    [self.loadingView removeFromSuperview];
  }
}
在每次需要加载菊花的时候,使用

[self showLoadingView]

[self hideLoadingView]

上一篇下一篇

猜你喜欢

热点阅读