在CollectionView(布局使用Flow)中的Cell,其大小以及位置都可以通过UICollectionViewDelegateFlowLayout类的代理方法进行设置。
1、预置条件
CollectionView的Layout类型为Flow。
2、设置Cell的大小
-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath
{
CGFloatscreenWith=[UIScreenmainScreen].bounds.size.width;
//每行2个Cell
CGFloatcellWidth=(screenWith-3*kSectionMargin)*0.5;
returnCGSizeMake(cellWidth,170);
}
3、设置Cell的边距
Cell的边距如下图所示,即Cell整体相对于Header、Footer以及屏幕左右两侧的距离,优先级较高;
//【整体】边距设置:整体边距的优先级,始终高于内部边距的优先级
-(UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
returnUIEdgeInsetsMake(kSectionMargin,kSectionMargin,kSectionMargin,kSectionMargin);//分别为上、左、下、右
}
4、设置Cell横向之间的距离
Cell与Cell横向之间的距离,如下图所示:
//每个item之间的间距
-(CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
returnkSectionMargin;
}
5、设置Cell纵向之间的距离
Cell纵向之间的距离,即行距,如下图所示
//每个section中不同的行之间的行间距
-(CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
returnkSectionMargin;
}