Last active
December 27, 2021 10:22
-
-
Save hamada147/9a6ec43a4a5e9a8bbf637360a8d55d5f to your computer and use it in GitHub Desktop.
Handle Select Cells in Collection View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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