1、设置Header和Footer
class(HeaderView,FooterView):NSView, NSCollectionViewElement{}复制代码
NSCollectionViewDataSource{ collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView}复制代码
kind:.sectionHeader,.sectionFooter
getView:
collectionView.makeSupplementaryView(ofKind: kind, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "header and footer"), for: indexPath)复制代码
2、固定Header和Footer
使用NSCollectionViewFlowLayout
let flowlayout = NSCollectionViewFlowLayout()flowlayout.sectionHeadersPinToVisibleBounds = trueflowlayout.sectionFootersPinToVisibleBounds = truecollectionview.collectionViewLayout = flowlayout复制代码
使用NSCollectionViewFlowLayout之后,默认的将会失效
flowlayout.itemSize = NSSize(width: 500, height: 84)flowlayout.headerReferenceSize = NSSize(width: 500, height: 150)flowlayout.footerReferenceSize = NSSize(width: 500, height: 48)//边距flowlayout.sectionInset = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)复制代码
3、动态设置item的Size
NSCollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize { //比如根据文字的 let nsstring: NSString = "string" let size = CGSize(width:1000, height:100) let dic = NSDictionary(object: NSFont.labelFont(ofSize: 13), forKey: NSAttributedStringKey.font as NSCopying) let new_size = nsstring.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: (dic as! [NSAttributedStringKey : Any]), context: nil).size return new_size//size(width:,height:) }}复制代码
4、Header、Footer不显示内容,尝试注册
collectionview.register(<#T##viewClass: AnyClass?##AnyClass?#>, forSupplementaryViewOfKind: <#T##NSCollectionView.SupplementaryElementKind#>, withIdentifier: <#T##NSUserInterfaceItemIdentifier#>)复制代码
forSupplementaryViewOfKind:.sectionHeader,.sectionFooter