Keep a reference to UICollectionView header

301 Views Asked by At

I need to store a view to use as a UICollectionView header. I don't want it to cycle out of memory though, because it needs to keep its state/data, etc.

With a table view you can just do tableView.tableHeaderView = view.

Here's what I'm trying:

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

        switch kind {
        case MagazineLayout.SupplementaryViewKind.sectionHeader:
            if let t = headerView { //headerView is an instance var
                return t
            } else {
                let view = collectionView.dequeueReusableSupplementaryView(ofKind: MagazineLayout.SupplementaryViewKind.sectionHeader, withReuseIdentifier: "MyHeaderView", for: indexPath) as! MyHeaderView
                view.titleLabel.text = "test"
                view.switch.addAction(for: .valueChanged, { [weak self] in
                    self?.switchValueChanged()
                })
                headerView = view
                return view
            }
        ...
    }

I don't want to re-create it every time the user scrolls it away and then back, so I'm trying to store a reference to it. This isn't working though. Hard to explain but the view it displays is cut off and the switch isn't responsive. If I comment out the "if" part and just create a new one every time, it looks correct but state is lost (i.e. the switch gets turned off) What's the best way to do this?

1

There are 1 best solutions below

1
Frankenstein On

Since you're keeping the reference and not letting it deallocate when it scrolls out of the view, remove the register and dequeuing entirely. It worked fine for me, here's how:

let view = MyHeaderView()
override func viewDidLoad() {
    super.viewDidLoad()
    view.titleLabel.text = "test"
    view.switch.addAction(for: .valueChanged, { [weak self] in
        self?.switchValueChanged()
    })
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    switch kind {
    case MagazineLayout.SupplementaryViewKind.sectionHeader:
        return view
        //...
    }
}