自定义UICollectionReusableView

来源:互联网 发布:掘金数据 编辑:程序博客网 时间:2024/06/04 00:35

使用UICollectionView自定义是对UI方面灵活运用的体现,UICollectionView对自定义的特殊样式方面有很大的帮助。今天先讲一下传统UICollectionView布局时遇到的UICollectionReusableView无法刷新的问题。

如果不知道原因的话在网上乱搜索只会搜到一个让你注册header的说法。但是一般情况下我们都会写注册方法的。但是还是无法回调header的协议方法。这是为什么呢?

经过跟collectionviewcell比对,我发现我们在自定义layout的时候只对uicollectionviewcell做出了UICollectionViewLayoutAttributes自定义,但是对header却没有单独注册。代码区别如下:
//这个是cell的自定义布局

 UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

//这个才是header的自定义布局方法

UICollectionViewLayoutAttributes *layoutAttributesHeader = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:indexPath];

我们既然注册了header,当然也要对header进行布局了。不过我们的-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath方法是不会单独对section的header或者footer进行一个循环布局的,例如我们第一个布局肯定是section=0 的header了,但是实际上这个方法走的是section=0时的cell=0的布局,所以我们需要再cell=0的时候同时另外添加对header的布局。

讲到这里大家应该就会对header的初级布局有个简单的了解。而不会找不出为什么我们的有些协议会不运行呢?

例如本章讲述的- (UICollectionReusableView *)collectionView:(UICollectionView *)cv viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath无法运行的问题。

好了今天先简单说下这个问题的原因和解决办法,主要的还是思想,我们要考虑下为什么会出现协议没有回调的问题。这样一步一步就会找到解决的办法了。

阅读全文
0 0
原创粉丝点击