iOS6.0之后,提供了UICollectionView。與UITableView相似,但是也有很多不同。
1、首先需要引入除了UICollectionViewDelegate,UICollectionViewDataSource之外的UICollectionViewDelegateFlowLayout。
2、在創(chuàng)建實例的時候,要注意
UICollectionView *collectionView = [UICollectionView new];
這樣生成會崩潰。必須是
//注意 UICollectionViewFlowLayout 不是UICollectionViewLayout。UICollectionViewFlowLayout是UICollectionViewLayout的子類。
UICollectionViewFlowLayout *collectionLayout = [UICollectionViewFlowLayout new];
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout: collectionLayout];
UICollectionViewFlowLayout用來控制布局的。有一些常用的屬性:
@property (nonatomic) CGFloat minimumLineSpacing;//每行的距離
@property (nonatomic) CGFloat minimumInteritemSpacing;//每個cell的距離
@property (nonatomic) CGSize itemSize;//每個cell的大小,如果每個cell的大小不一樣,就不要設(shè)置這個屬性。
@property (nonatomic) UIEdgeInsets sectionInset;//每個section的相對距離
@property (nonatomic) UICollectionViewScrollDirection scrollDirection;//視圖滑動的方向
在創(chuàng)建完UICollectionView實例后,才能設(shè)置上面的屬性。否則是無效的。
3、UICollectionView 也有UITableView一樣的方法
- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
在實現(xiàn)的時候,卻是不同的。UICollectionViewCell不需要判斷是否為空。在視圖初始化的時候,必須注冊Cell,系統(tǒng)生成在緩沖區(qū)中自動獲取。
錯誤:
UICollectionViewCell *collectionCell = [UICollectionViewCell new];
if (! collectionCell)
{
collectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell"];
}
正確:
UICollectionViewCell *collectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell"];
4、很多時候是需要自定義UICollectionViewCell。在重寫創(chuàng)建方法的時候
-(id)init;//重寫這個方法是無效的。不會調(diào)用重寫的方法。
//應該使用-(id)initWithFrame:(CGRect)frame;
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
//需要調(diào)用的方法。
}
return self;
}
自定義UICollectionViewFlowLayout一個新類,可以實現(xiàn)很多酷炫的動畫。例如:引導頁、輪播圖、瀑布流視圖...