2

I am not able to update the data of the Header View of a CollectionView. This header view is a subclass of UICollectionReusableView.

I tried to call a method for reloading this data in different places but none of them is triggering the update. To see the updated data I have to close and open the app again.

Collection View:

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        guard kind == UICollectionView.elementKindSectionHeader else {
            fatalError("Unexpected element kind.")
        }

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ProfileHeaderView", for: indexPath) as! ProfileHeaderView

         header?.reloadData()
//        headerView.userNameLabel.text = defaults.string(forKey: "username")

        return headerView
    }

Header View:

class ProfileHeaderView: UICollectionReusableView {

    @IBOutlet weak var userNameLabel: UILabel!

    func reloadData() {

        let defaults = UserDefaults.standard
        usernameTextLabel.text = defaults.string(forKey: "username")

    }

I also tried to call reloadData() on ViewWillAppear and ViewDidAppear

Maruta
  • 1,063
  • 11
  • 24

1 Answers1

4

You can try getting the header, for example:

func reloadHeaderData() {
    guard let header = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: YourIndexPath) as? ProfileHeaderView else { return }
    header.reloadData()
}
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24
  • where should i call this? – Maruta Sep 14 '19 at 12:42
  • It depends on your project structure but you can call it when you need to refresh the header data. – Francesco Deliro Sep 14 '19 at 13:10
  • I don't know where to put this to make it work. I get many errors. What should i put as indexpath? it doesnt accept ints.. Isn't this the same as I am doing already with header.reloadData? – Maruta Sep 16 '19 at 01:34
  • Hum, from what I understand for your first question you were not able to refresh the header data, but now, reading your comments, I'm thinking that is something related to the first time you load the collection view, but, in this case, what are you doing in the UICollectionViewDataSource function is enough. Let's continue the conversation in chat: https://chat.stackexchange.com/rooms/98713/reload-data-not-working-in-headerview-in-swift – Francesco Deliro Sep 16 '19 at 07:19