user6023982
user6023982

Reputation: 423

Highlight cells in two CollectionView

I use two CollectionView in one ViewController. Each CollectionView has 5 cells. I also use isSelected to detect selected cell (and highlight selected cell) for each CollectionView. In each CollectionView, only one cell can be selected (highlighted).

Everything works as it should, but there is one problem.

In simulator, when I select a cell with an index from 0 to 3, everything works fine. But the problem becomes when I select a cell with index 4. This highlights cells with index 4 in both CollectionView.

This only happens when the cell with index 4 of another CollectionView is not visible on the screen (I use the horizontal scrolling for both collection views and only 3 of 5 cells are visible at one time on the screen).

Below the part of my code:

var selectIndex = 1

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == self.percentsCollectionView {
        let cell:PercentCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: percentsCellIdentifiers[indexPath.item], for: indexPath) as! PercentCollectionViewCell

        if selectIndex == (indexPath as NSIndexPath).row
        {
            cell.isSelected = true
        }
        else
        {
            cell.isSelected = false
        }
        return cell
    }

    else {
        let cell:PersonCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: personsCellIdentifiers[indexPath.item], for: indexPath) as! PersonCollectionViewCell

        if selectIndex == (indexPath as NSIndexPath).row
        {
            cell.isSelected = true
        }
        else
        {
            cell.isSelected = false
        }
        return cell
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectIndex = (indexPath as NSIndexPath).row
    collectionView.reloadData()
    }

Upvotes: 0

Views: 210

Answers (1)

RJE
RJE

Reputation: 891

selectIndex = (indexPath as NSIndexPath).row collectionView.reloadData()

this part doesn't exactly says which collection view to select. its just the index and both collection view will get selected. The only reason you don't see this for 0-3 is that you are not reloading the other collection view. but the 4th index has to reload (when you scroll to see it) and it will get selected.

you have to use 2 different indexes for each collection view

eg:

selectIndex1 and selectIndex2

Upvotes: 1

Related Questions