NSCollectionView 基本使用

初始化以及基本配置

对应的VC实现NSCollectionViewDelegate,NSCollectionViewDataSource两个协议

//设置代理
self.collectionView.delegate = self
self.collectionView.dataSource = self
//是否可选中
self.collectionView.isSelectable = true
//注册cell
let nib = NSNib.init(nibNamed: NSNib.Name("HomeImgItem"), bundle: nil)
self.collectionView.register(nib, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "HomeImgItemId"))
//设置item的大小以及间距
let layout = self.collectionView.collectionViewLayout as! NSCollectionViewFlowLayout
layout.itemSize = .init(width: 120, height: 120)
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10

NSCollectionViewItem的使用

创建一个HomeImgItem继承于NSCollectionViewItem,并且一起创建xib
这里的NSCollectionViewItem继承的是NSViewController,和NSTableViewcell继承于view不同.

图片.png

xib中添加一个objct对象绑定到HomeImgItem,并做好相应的自动布局

图片.png
图片.png

实现代理方法

    //返回个数
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.dataArray.count
    }
    //返回对应的item自定义个体
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let view = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "HomeImgItemId"), for: indexPath) as! HomeImgItem
        let model = self.dataArray[indexPath.item]
        view.nameLabel.stringValue = model.name!
        if model.type == 0 {
            view.contentImgView.image = NSImage.init(named: NSImage.Name("NSFolder"))
            view.contentImgView.imageScaling = .scaleAxesIndependently
        }else{
            view.contentImgView.image = NSImage.init(contentsOf: URL.init(fileURLWithPath: model.url!))
            view.contentImgView.imageScaling = .scaleProportionallyDown
        }
        return view
    }
    
    
    
    //当item被选中
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set) {
        
        let view = collectionView.item(at: indexPaths.first!) as! HomeImgItem
        view.updateStatus()
    }
    
   //当item取消选中
    func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set) {
        let view = collectionView.item(at: indexPaths.first!) as! HomeImgItem
        view.updateStatus()
    }

HomeImgItem中可以根据isSelected参数来判断是否被选中,可以做一些背景颜色的切换功能

if isSelected == true {
    self.viewBg.layer?.backgroundColor = NSColor.lightGray.cgColor
}else{
    self.viewBg.layer?.backgroundColor = NSColor.white.cgColor
 }

实现鼠标双击以及右键单击

鼠标以及键盘的监听事件都来自于NSResponder
view,controller都继承于该类

override func mouseDown(with event: NSEvent) {
    super.mouseDown(with: event)
        
    if (event.pressure==1 && event.clickCount==2) {
        print("左键双击")
    }
        
}
    
override func rightMouseDown(with event: NSEvent) {
    super.rightMouseUp(with: event)
    print("右键点击")
}

最后效果

图片.png

你可能感兴趣的:(NSCollectionView 基本使用)