Search code examples
iosswiftuitableviewuicollectionviewuikit

Why after selecting cell programmatically - cell is not interaction?


I set a cell in the collectionView selected programmatically :

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(with: FAFavouriteCategoryCell.self, for: indexPath)!
        let currentCategory = categories[indexPath.row]
        cell.isSelected = selectedCategories.contains(currentCategory.categoryID)
        cell.configCell(category: currentCategory)
        return cell
    }

after this all selected cells not working. I can't click on It. If I clicked method shouldDeselectItemAt not calling


Solution

  • You need to call selectItem like this

      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(with: FAFavouriteCategoryCell.self, for: indexPath)!
            let currentCategory = categories[indexPath.row]
            if selectedCategories.contains(currentCategory.categoryID) {
                collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left) //Add this line
                cell.isSelected = true
            } else {
                collectionView.deselectItem(at: indexPath, animated: false)
                cell.isSelected = false
            }
            cell.configCell(category: currentCategory)
            return cell
        }