Search code examples
swiftuicollectionviewreloaddata

Collectionview Reloaddata function not working


I have a collectionView where I display the normal UICollectionViewCell with a UIButton inside. On another screen I have a list of switches. Whenever these change an update is sent to the screen with the collectionView. When a switch i turned off (and the dataSource is updated) I try to use the reloadData function to repopulate the collectionView. However, the buttons (cells) are displayed on top of each other.

I tried to use reloadData, doing it in the Dispatch.main.async, invalidating the collectionView, removing the deleteSections function and accessing the specific cell and removing it using cell.removeFromSuperView().

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
        let name = PickingState.getSelectedFilterValues()[indexPath.row]
        let button = SelectionsItem(title: name, frame: createMockupButtonToGetFrame(name: name))

        print(name)

        cell.contentView.addSubview(button)
        cell.contentView.addConstraintsWithFormat(formatString: "H:|[v0]|", views: button)
        cell.contentView.addConstraintsWithFormat(formatString: "V:|[v0]|", views: button)

        return cell
    }

Expect the cells to rerender and not be placed on top of each other.


Solution

  • The problem is here

    cell.contentView.addSubview(button)
    

    because of cell dequeuing you need to clear all buttons before add like

    cell.contentView.forEach { 
      if $0.tag == 22 {
         $0.removeFromSuperview()
      }
    }
    let button = SelectionsItem(title: name, frame: createMockupButtonToGetFrame(name: name))
    button.tag = 22
    cell.contentView.addSubview(button)
    

    Also don't forget

    button.translatesAutoresizingMaskIntoConstraints = false