NSCollectionView使用笔记

2,410 阅读1分钟
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)

使用NSCollectionViewFlowLayout

let flowlayout = NSCollectionViewFlowLayout()
flowlayout.sectionHeadersPinToVisibleBounds = true
flowlayout.sectionFootersPinToVisibleBounds = true

collectionview.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:)
    }
}
collectionview.register(<#T##viewClass: AnyClass?##AnyClass?#>, forSupplementaryViewOfKind: <#T##NSCollectionView.SupplementaryElementKind#>, withIdentifier: <#T##NSUserInterfaceItemIdentifier#>)

forSupplementaryViewOfKind:.sectionHeader,.sectionFooter

5、CollectionView的delegate和dataSource不设置会导致数据不显示之类的问题