UICollectionView with multi-select won't selec

2019-02-07 03:50发布

When using a UICollectionView with allowsMultipleSelection set to YES only a dozen items are selectable. UICollectionViewDelegate stops calling collectionView:didSelectItemAtIndexPath:.

It seems very random. You can select a few items, scroll down, select some more, and at some point you're not able to select any more items.

When the cell is smaller you seem to be able to select more items. The larger the cell, the fewer items you're able to select before it stops working.

1条回答
时光不老,我们不散
2楼-- · 2019-02-07 04:40

I have discovered that while my previous answer works, it may be caused by not calling super. While the documentation for UICollectionReusableView fails to mention this, the documentation for UITableViewCell, which has the same method, does.

- (void)prepareForReuse
{
    [super prepareForReuse]
    // Your code here.
}

Old Answer:


This may be a bug with the UICollectionView.

What's happening is cells that were previously selected are being reused and maintain the selected state. The collection view isn't setting selected to "NO".

The solution is to reset the the selected state in prepareForReuse of the cell:

- (void)prepareForReuse
{
    self.selected = NO;
}

If the reused cell is selected, the collection view will set selected to "YES" after prepareForReuse is called.

This is something the UICollectionView should be doing on it's own. Thankfully the solution is simple. Unfortunately I spent a ton of time working around this bug by tracking my own select state. I didn't realize why it was happening until I was working on another project with smaller cells.

查看更多
登录 后发表回答