iOS CollectionView的出現是一大福利,不再用用TableView來定義複雜的多欄表格了,用法與Table相似,只是Cell必須本身添加,無默認模式web
因爲CollectionView沒有默認的Cell佈局,因此通常仍是自定義方便又快捷佈局
1、自定義Cellspa
一、新建類CollectionCell繼承自UICollectionViewCell.net
![](http://static.javashuo.com/static/loading.gif)
二、新建Xib,命名爲CollectionCell.xib代理
![](http://static.javashuo.com/static/loading.gif)
a.選中CollectionCell.xib刪掉默認的View,從控件中拖一個Collection View Cell(圖3)到畫布中,設置大小爲95*116;code
b.選中剛剛添加的Cell,更改類名爲CollectionCell,如圖4orm
![](http://static.javashuo.com/static/loading.gif)
c.在CollectionCell.xib的CollectionCell中添加一個ImageView和一個Label(圖5)繼承
![](http://static.javashuo.com/static/loading.gif)
d.建立映射, 圖6,圖7事件
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
e.選中CollectionCell.m , 重寫init方法圖片
01 |
- (id)initWithFrame:(CGRect)frame |
03 |
self = [super initWithFrame:frame]; |
07 |
// 初始化時加載collectionCell.xib文件 |
08 |
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@ "CollectionCell" owner:self options: nil]; |
11 |
if (arrayOfViews.count < 1){ return nil;} |
13 |
// 若是xib中view不屬於UICollectionViewCell類,return nil |
14 |
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class ]]){ |
19 |
self = [arrayOfViews objectAtIndex:0]; |
2、定義UICollectionView;
一、拖動一個Collection View到指定ViewController的View上
二、連線dataSource和delegate,並建立映射,命名爲CollectionView
三、選中CollectionView的標尺,將Cell Size的Width和Height改爲與自定義的Cell同樣的95*116,圖8
四、選中CollectionView的屬性,能夠修改其屬性,好比是垂直滑動,仍是水平滑動,選擇Vertical或Horizontal
![](http://static.javashuo.com/static/loading.gif)
五、在ViewDidLoad方法中聲明Cell的類,在ViewDidLoad方法中添加,此句不聲明,將沒法加載,程序崩潰
1 |
// KCellID爲宏定義 @"CollectionCell" |
2 |
[self.collection registerClass:[CollectionCell class ] forCellWithReuseIdentifier:KCellID]; |
六、在ViewController.h中聲明代理
1 |
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate> |
七、在.m文件中實現代理方法
01 |
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section |
06 |
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath |
09 |
CollectionCell *cell = (CollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:KCellID forIndexPath:indexPath]; |
12 |
NSString *imageToLoad = [NSString stringWithFormat:@ "%d.JPG" , indexPath.row]; |
15 |
cell.label.text = [NSString stringWithFormat:@ "{%ld,%ld}" ,( long )indexPath.row,( long )indexPath.section]; |
18 |
cell.imageView.image = [UIImage imageNamed:imageToLoad]; |
效果如圖10
![](http://static.javashuo.com/static/loading.gif)
點擊某項後跳轉事件與UITableView相似,實現代理方法
1 |
-( void )collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath |
便可,不贅述