在我的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)
}
但是,当我将print()
放在viewForSupplementaryElementOfKind
函数中时,它永远不会执行。同样,没有红色标题出现。
这就是我设置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
}()
我在做什么错了?
答案 0 :(得分:0)
补充视图(页眉和页脚)不是集合视图项。您需要在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
,因此,除非使用这些技术中的一种,否则不会调用生成补充视图的方法。