UICollectionView很強大,tableView可以實現的功能,collectionView都可以實現,tableView實現不了的,它也能實現,但它在使用上與tableView有兩點區別 :
1.collectionView在使用的時候 必須要註冊cell,
2.必須創建一個佈局對象給collectionView。
// 註冊cell有三種方式:
1.可以通過在storyboard中給cell設置重用標識,即自動完成註冊(無需代碼)
2.通過xib文件註冊cell,並在註冊cell時,指定重用標識(可用控件collectionViewCell創建xib)
//獲得UINib對象,加載xib
UINib *nib = [UINib nibWithNibName:@"RCAppCell" bundle:nil];
RCAppCell *cell = [[nib instantiateWithOwner:nil options:nil]firstObject];
//通過xib註冊cell
[self.collectionView registerNib:nibforCellWithReuseIdentifier:@"cell"];
//代碼創建的時候,爲了拿到itemSize給它賦值,可以強轉一下
UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
// 如果cell是通過xib來創建的,cell的itemSize最好用xib中的cell的大小來動態的去設置"代碼更有擴展性"
layout.itemSize = cell.frame.size;
3.通過class來註冊一個cell,同時也要指定重用標識
//創建一個佈局對象,默認是沒有“格子(cell)”的大小和間距等屬性的,是空的佈局對象,在下面返回cell的時候,cell沒有Frame,所以運行不會顯示cell,要創建一個流佈局對象
//創建流佈局對象
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayoutalloc] init];
//給流佈局對象的itemSize屬性賦值
layout.itemSize = CGSizeMake(100, 120);
//創建collectionView的同時,必須同時設置一個佈局對象collectionViewlayout
UICollectionView *testView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
testView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:testView];
// 註冊cell"之前必須告訴collectView他將來所需要的cell該如何去創建"
// 通過一個類來註冊的cell,通過純代碼來自定義cell進用類來註冊
[testView registerClass:[RCAppCell class]forCellWithReuseIdentifier:@"cell"];