关于UICollectionView的使用(仅作为个人笔记,相关原理资料请查看文章尾部的《相关链接》)

来源:互联网 发布:云计算平台 开源软件 编辑:程序博客网 时间:2024/06/05 17:02

UICollectionView的结构组成:

1、Cells:用于展示内容的主体,对于不同的cell可以指定不同的尺寸和不同的内容;

2、Supplementary Views:即追加视图,类似于TableView的分段Section的Header或者Footer;

3、Decoration Views:装饰视图,这是Section的背景。


自定义UICollectionViewLayout:

UICollectionViewLayout的功能为向UICollectionView提供布局信息,包括Cell、追加视图和装饰视图的布局信息。实现一个自定义layout的常规做法是继承UICollectionViewLayout类,然后重载下列方法:

-(void)prepareLayout

做一些初始化操作(注意一定要调用[super  prepareLayout]


-(CGSize)collectionViewContentSize(可选实现)

返回collectionView的内容尺寸。

-(NSArray*)layoutAttributesForElementInRect:(CGRect)rect

1、返回rect中所有元素的布局信息;返回值为包含UICollectionViewLayoutAttributes的NSArray。

2、通过不同的UICollectionViewLayoutAttributes初始化方法可以获取对应的UICollectionViewLayoutAttributes:

1、layoutAttributesForCellWithIndexPath:

2、layoutAttributesForSupplementaryViewOfKind:withIndexPath:(按需实现)

3、layoutAttributesForDecorationViewOfKind:withIndexPath:(按需实现)


-(UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath*)indexPath

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

当边界发生改变时,是否刷新布局;


最后总结:在初始化一个UICollectionViewLayout实例后,一系列的准备方法将被自动调用,以保证layout实例的正确。

1、首先-(void)prepareLayout将被调用,默认该方法什么都没做,但是在自己的子类实现中,一般在该方法中设定一些必要的layout的结构和初始需要的结构和初始需要的参数等。

2、然后,-(CGSize)collectionViewContentSize将被调用,以确定collectionView应该占据的尺寸;该尺寸指的是所有内容所占的尺寸。

3、接下来-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect被调用;初始化的layout的外观将由该方法返回的UICollectionViewLayoutAttributes来决定。


注:当需要更新layout的时候,需要给当前的layout发送-invalidateLayout;

该消息立即返回,并且预约下一个loop的时候刷新当前的layout,这一点类似于UIView的setNeedsLayout方法。

(在-invalidateLayout后的下一个collectionView的刷新loop中,又会从prepareLayout开始,依次调用-collectionViewContentSize和-layoutAttributesForElementsInRects来生成更新后的布局)

相关示意图:




总结实现自定义UICollectionView必须实现的方法:

1、-(void)prepareLayout

[super prepare];//必须调用super

2、-(CGSize)collectionViewContentSize《设置该属性,才能滑动》


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

4、-(NSArray<UICollectionViewLayoutAttribute*s>)layoutAttributesForItemAtIndexPath:(NSIndexPath*)indexPath《按需实现supplementaryView或者DecorationView》

1、使用[UICollectionViewLayoutAttributes  layoutAttributesForCellWithIndexPath:indexPath]创建attribute 并设置相关attribute的属性;


5、-(BOOL)shouldInvalidateForLayoutForBounceChange《scrollView的bounce发生变化时调用》

6、-(CGPoint)targetContentOffsetForProposedContentOffset:withScrollingVelocity(可选实现)《滑动结束时设置最终的offset》




布局之间切换:

通过使用setCollectionViewLayout:animated:,则可以在切换布局的同时,使用动画来过渡。



相关资料:

UICollectionView详解(附带图解)

UICollectionViewLayout示例(瀑布流、滑动、圆形)

UICollectionView自定义布局详解(详细分步骤解说)

自定义UICollectionView代码实例(纯代码示例)


0 0
原创粉丝点击