初始化以及基本配置
对应的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
,和NSTableView
的cell
继承于view
不同.
在xib
中添加一个objct
对象绑定到HomeImgItem
,并做好相应的自动布局
实现代理方法
//返回个数
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<IndexPath>) {
let view = collectionView.item(at: indexPaths.first!) as! HomeImgItem
view.updateStatus()
}
//当item取消选中
func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
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("右键点击")
}
网友评论