UICollectionView

流水布局~UICollectionFlowLayout

瀑布流布局~流水布局~UICollectionLayout 继承 

## 自定义布局 - 继承UICollectionViewFlowLayout

### 重写prepareLayout方法

- 作用:在这个方法中做一些初始化操作

- 注意:一定要调用[super prepareLayout]

### 重写layoutAttributesForElementsInRect:方法

- 作用:

- 这个方法的返回值是个数组

- 这个数组中存放的都是UICollectionViewLayoutAttributes对象

- UICollectionViewLayoutAttributes对象决定了cell的排布方式(frame等)

### 重写shouldInvalidateLayoutForBoundsChange:方法

- 作用:如果返回YES,那么collectionView显示的范围发生改变时,就会重新刷新布局

- 一旦重新刷新布局,就会按顺序调用下面的方法:

- prepareLayout

- layoutAttributesForElementsInRect:

### 重写targetContentOffsetForProposedContentOffset:withScrollingVelocity:方法

- 作用:返回值决定了collectionView停止滚动时最终的偏移量(contentOffset)

- 参数:

- proposedContentOffset:原本情况下,collectionView停止滚动时最终的偏移量

- velocity:滚动速率,通过这个参数可以了解滚动的方向

CGFloat mainScreeWidth=[UIScreen mainScreen].bounds.size.width;

CGFloat mainScreeHight=200;

CGRect rect=CGRectMake(0, navView.frame.size.height+50, mainScreeWidth, mainScreeHight);

CollectionLineLayout *flowLayout=[[CollectionLineLayout alloc]init];

flowLayout.itemSize=CGSizeMake(120, 120);

flowLayout.scrollDirection=UICollectionViewScrollDirectionHorizontal;

UICollectionView *collective=[[UICollectionView alloc]initWithFrame:rect collectionViewLayout:flowLayout];

collective.delegate=self;

collective.dataSource=self;

注册cell

[collective registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CollectCell];

[self.view addSubview:collective];

数据源,数据方法

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

return  50;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

UICollectionViewCell *CollectionCellView=[collectionView dequeueReusableCellWithReuseIdentifier:CollectCell forIndexPath:indexPath];

CollectionCellView.backgroundColor=[UIColor orangeColor];

WXLog(@"%p,%ld",CollectionCellView,indexPath.item);

return CollectionCellView;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

WXLog(@"%zd",indexPath.row);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容