Skip to content

Instantly share code, notes, and snippets.

@hamada147
Last active December 27, 2021 10:22
Show Gist options
  • Save hamada147/9a6ec43a4a5e9a8bbf637360a8d55d5f to your computer and use it in GitHub Desktop.
Save hamada147/9a6ec43a4a5e9a8bbf637360a8d55d5f to your computer and use it in GitHub Desktop.
Handle Select Cells in Collection View
class ViewController: UIViewController, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Check whether there is any selected cell or not
if collectionView.indexPathsForSelectedItems?.count ?? 0 > 0 { // if there is an already selected cells
// check if selected cell indexPath is one of the indexPathsForSelectedItems
if collectionView.indexPathsForSelectedItems!.contains(indexPath) {
// if yes, deselect it
collectionView.deselectItem(at: indexPath, animated: true)
} else {
// if no, not specified what to do here => personal suggestion would be to update the selected cells
for row in 0..<indexPath.row {
collectionView.selectItem(at: IndexPath(row: row, section: indexPath.section), animated: true, scrollPosition: .centeredHorizontally)
}
}
} else { // this is the first cell to select
// Select all cells ending with the clicked one and starting from the first cell in same section
for row in 0..<indexPath.row {
collectionView.selectItem(at: IndexPath(row: row, section: indexPath.section), animated: true, scrollPosition: .centeredHorizontally)
}
}
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
// You can implement any logic you want here
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment