swiftuicollectionviewheaderinstagramsupplementary

Update CollectionView supplementaryView header when off screen


I have a view similar to Instagram's main stories feed. I have a horizontal collection view at the top where I have a supplementaryView header cell that looks the same but acts differently to the rest of the cells.

I am trying to update the objects in the supplementaryView which I have managed to do with the following code...

@objc func uploadCompleted() {

    DispatchQueue.main.async {
        self.collectionView.performBatchUpdates({
            if let myCell = self.collectionView.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: 0)) as? MyCollectionReusableView {
                // Do your stuff here
                myCell.nameLbl.textColor = .black
                ...
            }
        }, completion: nil)
    }
}

This works fine when the cell is in view, however when the cell is swiped off screen during this call it doesn't get updated.

Any ideas on how to get around this? Or a better approach to updating just the first cell in a collection view and not the rest.

Thanks


Solution

  • The header is not nil when it's visible you need

    var color = UIColor.red
    

    And inside viewForSupplementaryElementOfKind

    func collectionView(_ collectionView: UICollectionView, 
         viewForSupplementaryElementOfKind kind: String, 
                          at indexPath: IndexPath) -> UICollectionReusableView 
       let  myCell = //
       myCell.nameLbl.textColor = color
       return myCell
    }
    

    Then alter color where and when you want after the header appears again it'll be changed to the latest color

    @objc func uploadCompleted() {
    
        DispatchQueue.main.async {
            self.color = UIColor.black
            self.collectionView.performBatchUpdates({
                if let myCell = self.collectionView.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: 0)) as? MyCollectionReusableView {
                    // Do your stuff here
                    myCell.nameLbl.textColor = self.color
                    ...
                }
            }, completion: nil)
        }
    }