I have a UICollectionView that is a calendar. It's a single scrollable row. Some of the dates are unselectable as there is no data for that date. Others ARE selectable as there IS data for that date.
When a date is selected the calendar underlines the selected date and scrolls it to the center of the UICollectionView.
When a date is tapped that doesn't have a date I have this function...
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return //is there data for the date at this indexPath?
}
This stops those cells being selected... however, it still deselects the previously selected cell.
There is a shouldDeselect function but I can't use this as I don't know the index of the tapped cell. So I can't determine whether the item should be deselected.
Is there a better way of doing this?
It simple works for me when I reload the collectionview:
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
// return true whithout reloadData when necessarily
collectionView.reloadData()
return false
}
I recently had the same issue and I ended up with the following approach:
Whenever user selects a cell, remember the position in a member variable:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
myMemberVariable = indexPath.row
}
After that call myCollectionView.reloadData()
In the cellForRowAtIndexPath: apply appropriate configuration for the cell:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCell.identifier, for: indexPath) as! MyCell
if indexPath.row == myMemberVariable && canSelectCellAt(indexPath: indexPath) {
cell.backgroundColor = .green
} else {
cell.backgroundColor = .gray
}
return cell
}
Where canSelectCellAt(indexPath: indexPath) is a function, which returns true for selectable cells and false for non-selectable cells,
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