——周技术回顾

我们都知道如何给tableView添加headerView,实现起来比较简单,使用的场景也是比较多,但对于给collectionView添加header的场景就比较少了,今天做到个需求是需要给collectionView添加headerView遇到些问题。主要遇到以下两个问题:

*
问题一
我用的系统的UICollectionReusableView 那么就会出现一个问题,在header的地方你每次刷新他都会初始化一个view
,打开界面好多个headerView重叠在一起了,于是查了大佬们的方法,看到都是说判断这个view的subviews.count
如果为0那么就添加你要添加的子视图。对这样是解决了重叠的问题。

*
问题二
当你刷新的时候,你会发现你的headerView上面的数据错乱了,此时就应该是headerView
的复用的问题了。复用了之后直接将子视图也复用了,所以导致数据没有根据自己的indexPath.section
去赋值。整了半天没有明白怎么回事,然后就自定义了一个header,完美解决了这个问题。

自定义LHJCollectionReusableView
@interface LHJCollectionReusableView : UICollectionReusableView @end
@implementation LHJCollectionReusableView @end
collectionView 注册headerView
[collectionView registerClass:[MGSEpisodeViewAdHeaderView class]
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:@"LHJCollectionReusableView"];
collectionview实现代理方法操作headerView
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(
UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(
NSInteger)section { return CGSizeMake(UIScreen.mainScreen.bounds.size.width, 100
); } - (UICollectionReusableView *)collectionView:(UICollectionView *)
collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(
NSIndexPath*)indexPath { if ([kind isEqualToString:
UICollectionElementKindSectionHeader]) { LHJCollectionReusableView *headerView =
[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:
NSStringFromClass(LHJCollectionReusableView.class) forIndexPath:indexPath]; [
headerView removeAllSubviews]; // headerView上添加其他的view和控件 return headerView; }
return nil; }
<>总结

简单实现了collectionView的headerView,完美的实现了我的问题,如果有更好的小伙伴可以评论哈,也希望给遇到同样问题的小伙伴提供帮助。

技术
今日推荐
PPT
阅读数 121
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信