前言
UICollectionView进阶之路一
上一篇介绍了UICollectionView的基础和超级封装,我们抛弃了UICollectionView繁琐的数据源代理,虽然使用起来方便了很多,但还是有个大胆的想法,不写数据源代理,把UICollectionView的组成分为一个个小插件(widget)拼接而成。
可以?
...........
不可以?
...........
当然可以啦,(哈哈,有兴趣的同学跟我一起来了解实现方法吧)
UICollectionView插件化(widget)组成
- XWWidget,UICollectionView插件化的元件,负责整合每个插件的数据
-
UICollectionView+XWWidget,UICollectionView和XWWidget的直接交互,负责管理整合多个XWWidget,UICollectionView的数据源代理
XWWidget
- XWWidget结构
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef enum : NSUInteger {
XWWidgetStateDefault, // 正常状态
XWWidgetStateRequsting, // 正在请求刷新状态
XWWidgetStateRequestFail, // 请求刷新失败
XWWidgetStateRequestSuccess,// 请求刷新成功
XWWidgetStateRequestNoMoreData// 请求刷新无更多数据状态
} XWWidgetState;
@interface XWWidget : NSObject
@property (nonatomic , weak , readonly,nullable) UICollectionView *collectionView;
@property (nonatomic , assign ,readonly) XWWidgetState state; // 当前请求状态
/**
* 一个secion时候设置
*/
@property (nonatomic , strong , nullable) NSObject * headerData; // 头部视图数据
@property (nonatomic , strong , nullable) NSMutableArray * cellDataList; // cell视图模型数组
@property (nonatomic , strong , nullable) NSObject * footerData; // 尾部视图模型
@property (nonatomic , copy , nullable) Class decorationViewClass; // 修视背景图类
/**
* 多个secion时候设置
*/
@property(nonatomic , strong , nullable) NSMutableArray * headerDataList;
@property(nonatomic , strong , nullable) NSMutableArray< NSMutableArray * > * multiCellDataList;
@property(nonatomic , strong , nullable) NSMutableArray * footerDataList;
@property(nonatomic , strong , nullable) NSMutableArray<Class> * decorationViewClassList;
/**
刷新部件
*/
-(void) xw_reloadWidget;
/**
头部刷新请求回调 可重写
*/
- (void)requestHeaderRefresh;
/**
尾部刷新请求回调 可重写
*/
- (void)requestFooterRefresh;
/**
刷新请求完成调用
@param state 请求结果
*/
-(void)requestFinishWithState:(XWWidgetState)state;
/**
刷新请求完成 成功 调用
*/
-(void)requestSuccess;
/**
刷新请求完成 失败 调用
*/
-(void)requestFail;
/**
刷新请求完成 没有更多数据 (也属于成功) 调用
*/
-(void)requestNoMoreData;
@end
代码注释得很清楚,每一个XWWidget插件支持单个section和多个section,为了解耦,每个插件可以独立实现网络请求,你要做的是将页面合理的分为几个独立的widget,这样你就完成一半了。
UICollectionView+XWWidget
- UICollectionView+XWWidget结构
#import <UIKit/UIKit.h>
#import "XWWidget.h"
@interface UICollectionView (XWWidget)
/**
刷新所有部件
*/
-(void) xw_reloadWidgets;
/**
刷新部件
*/
-(void) xw_reloadWidget:(XWWidget *)widget;
/**
添加一个部件
*/
- (void)xw_addWidget:(XWWidget *) widget;
/**
插入一个部件
*/
- (void)xw_insertWidget:(XWWidget *) widget atIndex:(NSUInteger)index ;
/**
删除一个部件
*/
- (void)xw_removeWidget:(XWWidget *) widget;
/**
删除所有部件
*/
- (void)xw_removeAllWidgets;
/**
头部刷新
*/
-(void)xw_collectionViewHeaderRefresh;
/**
加载更多
*/
-(void)xw_collectionViewFooterRefresh;
/**
加载结束
*/
-(void)xw_endRefreshingWithWidgetState:(XWWidgetState)state;
@end
#import "UICollectionView+XWWidget.h"
#import <objc/runtime.h>
#import "UICollectionView+XW.h"
@interface UICollectionView ()
@property (nonatomic, strong) NSMutableArray * xw_headerDataList;
@property (nonatomic, strong) NSMutableArray * xw_cellDataList;
@property (nonatomic, strong) NSMutableArray * xw_footerDataList;
@property (nonatomic , strong) NSMutableArray * xw_decorationViewClassList;
@property (nonatomic , strong) NSMutableArray * xw_oldSectionList;
@property(nonatomic, strong) NSMutableArray *xw_widgets;
@end
@implementation UICollectionView (XWWidget)
#pragma mark - XWCollectionViewDataSource
- (NSMutableArray *)headerDataListWithCollectionView:(UICollectionView *) collectionView{
return self.xw_headerDataList;
}
- (NSMutableArray *)cellDataListWithCollectionView:(UICollectionView *) collectionView{
return self.xw_cellDataList;
}
- (NSMutableArray *)footerDataListWithCollectionView:(UICollectionView *) collectionView{
return self.xw_footerDataList;
}
- (NSMutableArray<Class> *)decorationViewClassListWithCollectionView:(UICollectionView *)collectionView{
return self.xw_decorationViewClassList;
}
#pragma mark - public
-(void) xw_reloadWidgets{
[self.xw_headerDataList removeAllObjects];
[self.xw_cellDataList removeAllObjects];
[self.xw_footerDataList removeAllObjects];
[self.xw_decorationViewClassList removeAllObjects];
for (XWWidget * widget in self.xw_widgets) {
[self.xw_headerDataList addObjectsFromArray:widget.headerDataList];
[self.xw_cellDataList addObjectsFromArray:widget.multiCellDataList];
[self.xw_footerDataList addObjectsFromArray:widget.footerDataList];
[self.xw_decorationViewClassList addObjectsFromArray:widget.decorationViewClassList];
}
self.xw_dataSource = (id<XWCollectionViewDataSource>)self;
dispatch_async(dispatch_get_main_queue(),^{
[UIView performWithoutAnimation:^{
//刷新界面
[CATransaction begin];
[CATransaction setDisableActions:YES];
[self reloadData];
[CATransaction commit];
}];
});
}
-(void) xw_reloadWidget:(XWWidget *)widget{
[self xw_reloadWidgets];
}
- (void)xw_addWidget:(XWWidget *) widget{
NSUInteger index = self.xw_widgets.count;
[self xw_insertWidget:widget atIndex:index];
}
- (void)xw_insertWidget:(XWWidget *) widget atIndex:(NSUInteger)index {
if ([widget isKindOfClass:[XWWidget class]] && self.xw_widgets.count <= index) {
if ([self xw_containWidget:widget] == false) {
[widget setValue:self forKey:@"collectionView"];
[self.xw_widgets insertObject:widget atIndex:index];
[self xw_delayReload];
}
}
}
- (void)xw_removeWidget:(XWWidget *) widget{
if ([self.xw_widgets containsObject:widget]) {
[self.xw_widgets removeObject:widget];
[self xw_delayReload];
}
}
- (void)xw_removeAllWidgets{
if (self.xw_widgets.count) {
[self.xw_widgets removeAllObjects];
[self xw_delayReload];
}
}
- (BOOL)xw_containWidget:(XWWidget *)widget{
return [self.xw_widgets containsObject:widget];
}
- (BOOL)xw_containWidgetClass:(Class) widgetClass{
for (XWWidget * sub in self.xw_widgets) {
if ([sub isMemberOfClass:widgetClass]) {
return true;
}
}
return false;
}
-(void)xw_collectionViewHeaderRefresh{
for (XWWidget * widget in self.xw_widgets) {
[widget setValue:@(true) forKey:@"needRequest"];
[widget requestHeaderRefresh];
}
}
-(void)xw_collectionViewFooterRefresh{
for (XWWidget * widget in self.xw_widgets) {
[widget setValue:@(true) forKey:@"needRequest"];
[widget requestFooterRefresh];
}
}
-(void)xw_endRefreshingWithWidgetState:(XWWidgetState)state{
}
/**
* 请求数据完毕时回调
*/
- (void)xw_requestFinish{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadAllWidgetsIfNeed) object:nil];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadData) object:nil];
// [self performSelectorOnMainThread:@selector(reloadAllWidgetsIfNeed) withObject:nil waitUntilDone:YES];
[self performSelector:@selector(reloadAllWidgetsIfNeed) withObject:nil afterDelay:0];
}
-(void)reloadAllWidgetsIfNeed{
BOOL need = true;
for (XWWidget * widget in self.xw_widgets) {
if (widget.state == XWWidgetStateRequsting) {
need = false;
break;
}
}
if (need) {
[self xw_reloadWidgets];
[self xw_endRefreshingWithWidgetState:self.xw_state];
}
}
#pragma mark - private
-(void) xw_delayReload{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(xw_reloadWidgets) object:nil];
[self performSelector:@selector(xw_reloadWidgets) withObject:nil afterDelay:0];
}
#pragma mark - getter setter
- (XWWidgetState)xw_state{
XWWidgetState state = XWWidgetStateDefault;
for (XWWidget * widget in self.xw_widgets) {
if (widget.state == XWWidgetStateRequsting) {
return XWWidgetStateRequsting;
}
}
for (XWWidget * widget in self.xw_widgets) {
if (widget.state == XWWidgetStateRequestNoMoreData) {
state = XWWidgetStateRequestNoMoreData;
break;
}
if (widget.state == XWWidgetStateRequestSuccess) {
state = XWWidgetStateRequestSuccess;
}
if (widget.state == XWWidgetStateRequestFail && state != XWWidgetStateRequestSuccess) {
state = XWWidgetStateRequestFail;
}
}
return state;
}
- (NSMutableArray *)xw_headerDataList{
NSMutableArray * list = objc_getAssociatedObject(self, @selector(xw_headerDataList));
if (!list) {
list = [NSMutableArray new];
objc_setAssociatedObject(self, @selector(xw_headerDataList), list, OBJC_ASSOCIATION_RETAIN);
}
return list;
}
- (void)setXw_headerDataList:(NSMutableArray *)xw_headerDataList{
objc_setAssociatedObject(self, @selector(xw_headerDataList), xw_headerDataList, OBJC_ASSOCIATION_RETAIN);
}
- (NSMutableArray *)xw_footerDataList{
NSMutableArray * list = objc_getAssociatedObject(self, @selector(xw_footerDataList));
if (!list) {
list = [NSMutableArray new];
objc_setAssociatedObject(self, @selector(xw_footerDataList), list, OBJC_ASSOCIATION_RETAIN);
}
return list;
}
- (void)setXw_footerDataList:(NSMutableArray *)xw_footerDataList{
objc_setAssociatedObject(self, @selector(xw_footerDataList), xw_footerDataList, OBJC_ASSOCIATION_RETAIN);
}
- (NSMutableArray *)xw_cellDataList{
NSMutableArray * list = objc_getAssociatedObject(self, @selector(xw_cellDataList));
if (!list) {
list = [NSMutableArray new];
objc_setAssociatedObject(self, @selector(xw_cellDataList), list, OBJC_ASSOCIATION_RETAIN);
}
return list;
}
- (void)setXw_cellDataList:(NSMutableArray *)xw_cellDataList{
objc_setAssociatedObject(self, @selector(xw_cellDataList), xw_cellDataList, OBJC_ASSOCIATION_RETAIN);
}
- (NSMutableArray *)xw_decorationViewClassList{
NSMutableArray * list = objc_getAssociatedObject(self, @selector(xw_decorationViewClassList));
if (!list) {
list = [NSMutableArray new];
objc_setAssociatedObject(self, @selector(xw_decorationViewClassList), list, OBJC_ASSOCIATION_RETAIN);
}
return list;
}
- (void)setXw_decorationViewClassList:(NSMutableArray *)xw_decorationViewClassList{
objc_setAssociatedObject(self, @selector(xw_decorationViewClassList), xw_decorationViewClassList, OBJC_ASSOCIATION_RETAIN);
}
- (NSMutableArray *)xw_widgets{
NSMutableArray * widgets = objc_getAssociatedObject(self, @selector(xw_widgets));
if (!widgets) {
widgets = [NSMutableArray new];
objc_setAssociatedObject(self, @selector(xw_widgets), widgets, OBJC_ASSOCIATION_RETAIN);
}
return widgets;
}
- (void)setXw_widgets:(NSMutableArray *)xw_widgets{
objc_setAssociatedObject(self, @selector(xw_widgets), xw_widgets, OBJC_ASSOCIATION_RETAIN);
}
@end
UICollectionView+XWWidget结构很好理解,具体代码如上(,仅代表个人风格,如有大神解决那里可以改善的可以联系我,一起探讨下),就几个方法,除了widget插件的管理,还有就是网络请求,刷新,加载更多和网络请求结束的回调。
实际应用
例如美团的首页,轮播图为一个widget,分类为一个widget,下面的商品或者其他的为一个widget,每个widget互相独立(网络请求,和响应时间独立),然后你要做的是把这几个widget拼接起来,不同的拼接顺序会产生预想不到的效果。
UICollectionView插件化的使用可以超乎你的想象,你要你够了解他,可以组合出各种使用可能
下面看具体实现代码:
//weak弱引用
#define KWeakSelf __weak typeof(&*self) weakSelf = self
#import "XWWidgetViewController.h"
#import "XWWidgetMacros.h"
#import "XWTest1Widget.h"
#import "XWTest2Widget.h"
@interface XWWidgetViewController ()<XWCollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,strong) UICollectionView *cv;
@end
@implementation XWWidgetViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self creatUI];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)creatUI{
[self.view addSubview:self.cv];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
NSLog(@"drag...");
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"scroll-viewcontroller...");
}
-(UICollectionView *)cv{
if (_cv == nil) {
_cv = [UICollectionView createWithFlowLayout];
_cv.frame = self.view.bounds;
_cv.backgroundColor = [UIColor whiteColor];
// _cv.alwaysBounceVertical = YES;
[_cv xw_addWidget:[[XWTest1Widget alloc]init]];
[_cv xw_addWidget:[[XWTest2Widget alloc]init]];
[_cv.xw_delegates addObject:self];
}
return _cv;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)dealloc{
NSLog(@"XWWidgetViewController dealloc");
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
- XWTest1Widget
@interface XWTest1Widget ()
@end
@implementation XWTest1Widget
-(instancetype)init{
if (self = [super init]) {
[self creatCellData];
}
return self;
}
-(void)creatCellData{
NSObject *header = [NSObject new];
header.xw_height = 0.01;
header.xw_width = [UIScreen mainScreen].bounds.size.width;
header.cell_secionInset = UIEdgeInsetsMake(10, 0, 10, 0);
header.cell_minimumLineSpacing = 10;
header.cell_minimumInteritemSpacing = 10;
self.headerData = header;
NSMutableArray *cells = [NSMutableArray array];
for (int i = 0; i < 20; i++) {
[cells addObject:[[XWTest1Data alloc]init] ];
}
self.cellDataList = cells;
}
@end
- XWTest2Widget
@interface XWTest2Widget ()
@end
@implementation XWTest2Widget
-(instancetype)init{
if (self = [super init]) {
[self creatCellData];
}
return self;
}
-(void)creatCellData{
NSObject *header = [NSObject new];
header.xw_height = 50;
header.xw_width = [UIScreen mainScreen].bounds.size.width;
header.cell_secionInset = UIEdgeInsetsMake(5, 0, 5, 0);
header.cell_minimumLineSpacing = 5;
header.cell_minimumInteritemSpacing = 5;
self.headerData = header;
NSMutableArray *cells = [NSMutableArray array];
for (int i = 0; i < 20; i++) {
[cells addObject:[[XWTest1Data alloc]init] ];
}
self.cellDataList = cells;
}
@end
从代码可以看出代码结构很清晰,业务层面看不到UICollectionVie w繁琐的数据源代理,当然了点击事件和其他代理可以在cell上实现也可以由具体业务实现,内部也扩展了多代理转发机制。
写在最后
UICollectionView插件化优点
- 代码结构清晰,由数据驱动视图(数据即视图),解决控制器臃肿,代码容易阅读
- 提高开发效率,项目中离不开列表,UITableView和UICollectionView的数据源代理几乎无处不在,UICollectionView插件化很好的解决了这一痛点
- 后期可维护性强,只要做好合理分widget,后期修改某个插件内的内容,或者新增删除某个插件,只要管理widget即可
- 可复用性强,有做过电商和内容内的项目都知道,往往某一块内容多处可见,这时候你只需要来个通用的Widget即可,哪里需要哪里add
闲言杂语
GitHub: https://github.com/WangJianShi/UICollectionView-Widget