I have a Horizontal UICollectionView like the horizontal Calender in iOS. Paging is enabled but not allowsMultipleSelection.
self.allowsMultipleSelection = fals
Take a class-level variable, say index
var index = -1
As you have said that multiple selections are not allowed so the following will do the job for you
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
index = indexPath.item
collectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
if let cell = cell {
cell.backgroundColor = indexPath.item == index ? .red : .white
}
}
Whenever user tap on any cell we save the position in index
variable and then call the reloadData() to notify collectionView about the change
In cellForRowAt
we check if the current cell us selected we set the color to red otherwise white