collectionView布局

时间:2023-03-09 08:48:57
collectionView布局

关于 collectionView的layout布局方法:

设置cell的间距,行间距,组与组之间的间距,都是在layout里面来设置.

包括,滚动方向.

-(void)prepareLayout

[super prepareLayout]

//最小行间距

self.minimumLineSpacing =1;

//最小cell间距

self.minimumInteritemSpacing =1;

//组与组之间的间距

self.sectionInset =UIEdgeInsetsMake(0, 0, 20, 0);

}

设置cell的大小有两种方法

一种在layout布局里面来通过方法,设置cell的大小

方法名称比较长,只要记住layout的关键字返回值是一个数组

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{

NSArray *attrs =[super layoutAttributesForElementsInRect:rect];

for (UICollectionViewLayoutAttributes *attr in attrs) {

//如果是第一组,进行操作..

//获取frame

CGRect frame = attr.frame;

CGFloat height =100;

CGFloat width =(self.collectionView.frame.size.width -3)/4;

if (attr.indexPath.section ==1) {

//frame = CGRectMake(0, 0, self.collectionView.frame.size.width, 100);//不要修改他的位置,只需要修改他的大小

//修改frame

frame.size =CGSizeMake(self.collectionView.frame.size.width, height);

}else{

frame.size =CGSizeMake(width, height);

}

//赋值回去

attr.frame =frame;

}

return attrs;

}

第二种方法:

遵守协议

//实现代理方法

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

CGFloat height = 100;

CGFloat width =(collectionView.frame.size.width-3)/4;

if (indexPath.section ==1) {

return CGSizeMake(collectionView.frame.size.width, 120);

}

return CGSizeMake(width, height);

}

-(void)prepareLayout{

[super prepareLayout];

//最小行间距

self.minimumLineSpacing =1;

//最小cell间距

self.minimumInteritemSpacing =1;

//组与组之间的间距

self.sectionInset =UIEdgeInsetsMake(0, 0, 20, 0);

CGFloat height =100;

CGFloat width =(self.collectionView.frame.size.width -3)/4;

self.itemSize =CGSizeMake(width, height);

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//上面的布局问题:需要初始时候先指定一个大小. 当初始位置有了大小,让布局,按照这个大小来进行布局

//没有给大小,他会按照默认的大小,50,50来计算,所以会导致cell直接压在一起.

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{

NSArray *attrs =[super layoutAttributesForElementsInRect:rect];

for (UICollectionViewLayoutAttributes *attr in attrs) {

//如果是第一组,进行操作..

//获取frame

CGRect frame = attr.frame;

if (attr.indexPath.section ==1) {

frame.size =CGSizeMake(self.collectionView.frame.size.width, 100);

}

//赋值回去

attr.frame =frame;

}

return attrs;

}

@end