user4992124
user4992124

Reputation: 1594

NSCollectionView viewForSupplementaryElementOfKind not being called

In my NSCollectionViewItem I set up the code below.

func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
    let view = collectionView.makeSupplementaryView(ofKind: .sectionHeader, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "sectionHeader"), for: indexPath)
    view.wantsLayer = true
    view.layer?.backgroundColor = NSColor.red.cgColor
    return view       
}

func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
    return NSSize(width: self.frame.size.width, height: 60)
}

However, when I place a print() in the viewForSupplementaryElementOfKind function it never is executed. Also, no red header appears.

This is how I set up the NSCollectionView

public let collectionView: NSCollectionView = {
    let v = NSCollectionView(frame: NSRect.zero)
    v.wantsLayer = true
    v.layer!.backgroundColor = NSColor.clear.cgColor
    v.isSelectable = true
    v.backgroundColors = [NSColor.clear]
    v.allowsEmptySelection = false
    v.collectionViewLayout = {
        let l = NSCollectionViewFlowLayout()
        l.minimumInteritemSpacing = 1
        l.minimumLineSpacing = 1
        l.scrollDirection = NSCollectionView.ScrollDirection.vertical
        l.sectionInset = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        return l
    }()

    return v
}()

What am I doing wrong?

Upvotes: 2

Views: 961

Answers (1)

Brett
Brett

Reputation: 4391

The supplemental views (header and footer) are not collection view items. You need to implement those two methods on the NSCollectionViewDelgateFlowLayout object, not on your NSCollectionViewItem class.

See https://developer.apple.com/documentation/appkit/nscollectionviewdelegateflowlayout

You can also set a default for the entire collection view:

l.headerReferenceSize = NSSize(width: 0, height: 50)
l.footerReferenceSize = NSSize(width: 0, height: 50)

When using NSCollectionViewFlowLayout, the default size of the header and footer is NSSize.zero, so the method to make the supplemental view is not called unless one of these techniques is used.

Upvotes: 1

Related Questions