1

I have a (horizontal) collectionView which is in tableViewCell.

My tableViewCell row has a label and collectionView

Collectionview has button in each cell

enter image description here

When button is tapped, I highlight the button's color and tableCell's row which is perfectly working. I have problem with prepareForReuse()

Scenario: I tapped on button and it changes its color(in collectionCell) and highlights tableViewCell's row and I have 10+ tablerows. When I scroll down tableView, I see the selection I made on tableRow1 appears in tableRow10

I added prepareForReuse() in tableviewcell but how can i reference and reset the button appearance which is inside collectionview from table's prepareForReuse()

Please advice

    // This is my tableCell reuse method
    override func prepareForReuse() {
        super.prepareForReuse()
        tableCellLabel.text = nil
        // Reset collectionViewCell button display here
    }

   // This is my collectionView Datasource method:
   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ActivitySlotCollectionViewCell.identifier, for: indexPath) as! ActivitySlotCollectionViewCell
            cell.configure(from: dataModel)
           return cell
       }

  // This is my collectionViewCell reuseMethod
  override func prepareForReuse() {
        super.prepareForReuse()
        isButtonSelected = false
        slotButton.setTitleColor(UIColor.blue, for: .normal)
        slotButton.layer.borderColor = isButtonSelected ? UIColor.white.cgColor : UIColor.black.cgColor
        slotButton.backgroundColor = isButtonSelected ? UIColor.red : UIColor.clear
    }
Ashh
  • 569
  • 1
  • 6
  • 28

2 Answers2

0

Check the below link. Each time we dequeue a reuseable cell we need to clean it, actually this last disappeared cell. For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state. The table view' s delegate in tableView(_:cellForRowAt:) should always reset all content when reusing a cell.

Check this link

almost same for tableView and collectionView

0

Try to add this inside the prepareForReuse() function because basically you're not setting the default design for the cell that's being reuse that is why you see the selection you made on tableRow1 appears in tableRow10

slotButton.layer.borderColor = UIColor.black.cgColor

slotButton.backgroundColor = UIColor.clear

  • Hi Nathaniel Gonzales, thanks..this solved my tableView issue but the main issue i have is with the button appearance in the collectionviewCell – Ashh Sep 23 '20 at 03:36
  • can you explain more what appearance are referring with the button, do you want it to reset it to default design once you unselect it? – Nathaniel Gonzales Sep 24 '20 at 07:48