背景
看简书APP,发现当网络不是很好,它的banner数据没有加载出来的时候,banner中有一个indicator提示用户正在加载数据。
想到以后自己可能也会遇到类似需求,所以就简单封装了一下这个小功能。效果如下:
loading.gif
思路
给UIView添加一个indicatorView,需要的时候就展示出来,不要的时候就移除。
代码
扩展UIView:
#import "UIView+CQLoading.h" #import@interface UIView () /** loading view */ @property (nonatomic, strong) UIActivityIndicatorView *cq_loadingView; @end @implementation UIView (CQLoading) static void *cq_loadingViewKey = &cq_loadingViewKey; - (UIActivityIndicatorView *)cq_loadingView { return objc_getAssociatedObject(self, &cq_loadingViewKey); } - (void)setCq_loadingView:(UIActivityIndicatorView *)cq_loadingView { objc_setAssociatedObject(self, &cq_loadingViewKey, cq_loadingView, OBJC_ASSOCIATION_RETAIN); } /** 展示loading(默认灰色) */ - (void)cq_showLoading { // 默认展示灰色loading [self cq_showLoadingWithColor:[UIColor grayColor]]; } /** 展示指定颜色的loading @param color loading的颜色 */ - (void)cq_showLoadingWithColor:(UIColor *)color { if (self.cq_loadingView) { [self.cq_loadingView removeFromSuperview]; self.cq_loadingView = nil; } self.cq_loadingView = [[UIActivityIndicatorView alloc] initWithFrame:self.bounds]; [self addSubview:self.cq_loadingView]; self.cq_loadingView.color = color; [self.cq_loadingView startAnimating]; self.cq_loadingView.userInteractionEnabled = NO; } /** 移除loading */ - (void)cq_removeLoading { if (self.cq_loadingView) { [self.cq_loadingView removeFromSuperview]; self.cq_loadingView = nil; } } @end
使用
[imageView cq_showLoading]; // 展示loading [imageView cq_removeLoading]; // 移除loading