collectionView注册cell和筛选项问题

使用xib创建的cell、header、footer的register问题

通常向collectionView注册cell、header、footer时,我们会使用:

1
2
3
4
5
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellId];

[collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];

[collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];

但是,如果cell、header、footer是使用xib创建的,就会发现这样注册到collectionView,collectionView的内容展示不出来。这时候就需要使用Nib文件来实现:

1
2
3
4
5
6
7
/*cell*/
UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:[NSBundle mainBundle]];
[collectionView registerNib:cellNib forCellWithReuseIdentifier:@"myCellId"];

/*headerView*/
UINib *headerNib = [UINib nibWithNibName:@"MyHeader" bundle:[NSBundle mainBundle]];
[collectionView registerNib:headerNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myHeaderId"];

多个section 每个section只能被选中一项,且每个section里的item都是可选的,怎么实现?

经常会遇到这样的需求:在某个页面需要展示筛选项,筛选项有几个类,每个类里面有很多可以单选的选项,类与类之间的选项是并列可选关系,比如添加到购物车里的衣服的尺码和颜色、筛选历史订单中差评和订单商品类型等。这时如果选择使用collectionView来实现,就可以给各个类分成不同的section。

首先来说说遇到的问题:

比如生成了两个section,section0和section1,

  • 如果设置collectionView.allowsMultipleSelection = YES;,可以实现多选,但同时出现的问题是——每个section里的选项就不是单选了,而是可以选任意多个。
  • 如果不做设置,那么在整个collectionView中只能选择一个选项。

解决方法步骤:

1>为每个section定义一个成员变量记录当前section中被选中的index;

2>在cellForItemAtIndexPath中根据(indexPath.item== 该section的成员index)来设置cell.selected = YES;

3>在didSelectItemAtIndexPath方法中设置各section的成员index之后reload collectionView

4>在cell中重写setSelected方法 设置选中和非选中效果

如果需要有默认选项,给成员index设置一个默认值即可。

demo地址:

https://github.com/zhengry/ZZCollectionView