【问题标题】:NSCollectionView viewForSupplementaryElementOfKind not being calledNSCollectionView viewForSupplementaryElementOfKind 未被调用
【发布时间】:2019-01-17 10:08:23
【问题描述】:

在我的NSCollectionViewItem 中,我设置了以下代码。

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)
}

但是,当我在 viewForSupplementaryElementOfKind 函数中放置 print() 时,它永远不会被执行。此外,不会出现红色标题。

这就是我设置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
}()

我做错了什么?

【问题讨论】:

    标签: swift macos nscollectionview


    【解决方案1】:

    补充视图(页眉和页脚)不是集合视图项。您需要在 NSCollectionViewDelgateFlowLayout 对象上实现这两个方法,而不是在您的 NSCollectionViewItem 类上。

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

    您还可以为整个集合视图设置默认值:

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

    使用NSCollectionViewFlowLayout时,页眉和页脚的默认大小为NSSize.zero,因此除非使用其中一种技术,否则不会调用制作补充视图的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2021-09-21
      • 1970-01-01
      相关资源
      最近更新 更多