UICollectionView是iOS中一种非常重要的控件,继承自UITableView,和Android中的RecycleView也是类似的,常常用在使用瀑布流的界面中,目前已经越来越常见了。今天我们将会来实现如何对CollectionView中的Cell和Section进行动态的增加,并实现对Header头部标题进行动态的添加修改。此时将不再是静态呈现一个瀑布流的视图了。
我已经把项目放到了Github中 https://github.com/chenyufeng1991/CollectionView 。欢迎大家下载使用。其中包括了多种实现CollectionView的方式:storyboard,nib文件,纯代码。
首先主要要实现UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout这三个协议。CollectionView的数据源设置,点击方法和CollectionView的布局都是通过里面的代理方法实现的。
然后对于动态的增加Cell和Section,我们使用Lazy Load懒加载实现。懒加载在UI交互设计中非常常用,原理就是数据不必事先全部定义好,可以再后来增加,然后再刷新界面。
主要代码实现如下:(不想看的话可以直接从Github下载)
#import "SecondViewController.h"
#import "CollectionViewCell.h"
#import "AppDelegate.h"
#import "CollectionReusableView.h"
#define UISCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
@interface SecondViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//开始使用二维数组进行数据结构设计;
@property (nonatomic, strong)NSArray *defaultArray;//有defaultArray()方法;
@property (nonatomic, strong)NSMutableArray *dataArray;//有一个方法的名称也是dataArray();
//下面数组用来存放头部标题;
@property(strong,nonatomic) NSMutableArray *headerArray;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
//进行CollectionView和Cell的绑定
[self.collectionView registerClass:[CollectionViewCell class] forCellWithReus