iOS-UICollectionView自定义布局

时间:2023-03-08 23:01:43
iOS-UICollectionView自定义布局

UICollectionView自定义布局

转载:

http://answerhuang.duapp.com/index.php/2013/11/20/custom_collection_view_layouts/

主要属性介绍

UITableView和UICollectionView都是由data-source和delegate驱动的.使用起来两者相似.

UICollectionViewCell相当于table view中的cell, 用法也是一样的.

Supplementary views相当于table view的section header和footer views。像cells一样,他们的内容都由数据源对象驱动。然而,和table view中用法不一样的是,supplementary view并不一定会作为header或footer view;他们的数量和放置的位置完全由布局控制。从这个角度来讲,和cell差不多.

Decoration views纯粹为一个装饰品。他们完全属于布局对象,并被布局对象管理,他们并不从数据源获取他们的contents。当布局对象指定它需要一个decoration view的时候,collection view会自动创建,并为其应用布局对象提供的布局参数。并不需要准备任何自定义视图的内容。

UICollectionViewCell, Supplementary views和decoration views必须是UICollectionResuableView的子类。每个你布局所使用的视图类都需要在collection view中注册,这样当data source让他从reuse pool中出列时,它才能够创建新的实例。

自定义布局用到函数介绍

-(CGSize)collectionViewContentSize

用来确定collectionView的ContentSize的大小

layoutAttributesForElementsInRect:

关键函数, 用来控制cell, Supplementary view, 还有Decoration view的自定义布局属性, 将这些自定义布局属性组成这个数组, 返回. 这些自动布局属性,分别通过下面的三个函数来获取的layoutAttributesForItemAtIndexPath, layoutAttributesForSupplementaryViewOfKind, layoutAttributesForDecorationViewOfKind

-(UICollectionViewLayoutAttributes )layoutAttributesForItemAtIndexPath:(NSIndexPath )indexPath

获取cell的自动布局属性

-layoutAttributesForSupplementaryViewOfKind:withIndexPath:

获取SupplementaryView的自动布局属性

-layoutAttributesForDecorationViewOfKind:withIndexPath:,

获取DecorationView的自动布局属性

-shouldInvalidateLayoutForBoundsChange:

当bound变化的时候, 调用此函数. 如果返回yes, 将调用layoutAttributesForElementsInRect等一系列函数, 重新获取各个元素的自动布局.

例子:

下面为自己写的一个例子:

iOS-UICollectionView自定义布局

地址为: http://download.****.net/detail/daiyibo123/9144827