How to get the selected cells count and selected cells array from UICollectionView, I need to set the limit of selection. Below is my code which is not working. Please guide. Thanks
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
let indexPaths = collectionView.indexPathsForSelectedItems!
print(indexPaths)
if let selectedItems = collectionView.indexPathsForSelectedItems {
if selectedItems.count >= 3 {
collectionView.deselectItem(at: indexPath as IndexPath, animated: true)
return false
}
}
return true
}
Above code when written in didSelect method returns only selected cell index but here just skip to last line
return true
2
Answers
You can use the
shouldSelectItemAt
delegate method from theUICollectionViewDelegate
to achieve that:A sample demo to demonstrate how it works:
When you reach the selection limit,
shouldSelectItemAt
will return false anddidSelectItemAt
function will not be called anymore. On the other hand if you click on the already selected cell,didDeselectItemAt
will be called and you will be called, and you are able to select + 1 cell again, as the number of selected items will decrease with 1. See also the debug logs in the example.A better approach is model based.
In your data model add a property
and re-/set it accordingly when a cell is de-/selected.
Then you can simply count the selected data source items –
dataSource
represents the data source arrayFurther there is no need to deselect a row in this method as you are preventing the user from selecting more than 2 rows.