I am implementing a UICollectionView with multiple selection enabled.
Some of my cells are selectable, some are not. Here is the chain of events:
YES
to
shouldHighlightItemAtIndexPath:
shouldSelectItemAtIndexPath:
NO
to shouldSelectItemAtIndexPath:
)didDeselectItemAtIndexPath:
is called on them. NOTE: shouldDeselectItemAtIndexPath:
is not called.Expected Result: Nothing happens.
Is this normal behavior? I can't find anything in the docs. If so, how can I go about not deselecting my cells?
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue...
cell.userInteractionEnabled = isSelectableIndexPath(indexPath)
return cell
}
func isSelectableIndexPath(indexPath: NSIndexPath) -> Bool {
//logic to check if cell is selectable
}
This works by disabling interaction with the cell.
I had to face exactly the same problem, with collectionView:shouldDeselectItemAtIndexPath:
not being called. My solution consist of manually reselect the currently selected cell if I'm tapping on a non-selectable one:
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
BOOL isSelectable = /* decide if currently tapped cell should be selectable */;
NSIndexPath *selectedItemIndexPath = /* NSIndexPath of the current selected cell in the collection view, set in collectionView:didSelectItemAtIndexPath: */;
if (!isSelectable) {
// the cell isn't selectable, we have to reselect the previously selected cell that has lost selection in the meanwhile
// without reloading first the cell the selection is not working...
[collectionView reloadItemsAtIndexPaths:@[selectedItemIndexPath]];
[collectionView selectItemAtIndexPath:selectedItemIndexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
}
return isSelectable;
}
If your collection view is scrolling (hiding the currently selected cell) remember to reselect the cell in collectionView:cellForItemAtIndexPath:
.
I don't like too much this solution, it's too "hacky", but it works. I would expect to do all the logic in the collectionView:shouldDeselectItemAtIndexPath:
but it isn't called and I don't understand why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With