NSCollectionView单选不行,多选没问题

NSCollectionView single selection is not working, but multiple selection is fine

如标题所述, 单选时我的 NSCollectionView 不工作。

MyNSCollectionView 正确呈现,

下面的代码展示了我如何初始化我的 NSCollectionView:

    self.leftBar.dataSource = self
    self.leftBar.delegate = self

    self.leftBar.isSelectable = true
    self.leftBar.allowsEmptySelection = true

    let layout = NSCollectionViewFlowLayout()
    layout.scrollDirection = .horizontal

    layout.itemSize = NSSize(width: 200 , height: 50)

    leftBar.collectionViewLayout = layout


    self.contentView.addSubview(leftBar)

    leftBar <- [
        Top(),
        Left(),
        Bottom(),
        Width(200)
    ]

自定义 NSCollectionViewItem

class LeftBarCell: NSCollectionViewItem {

var leftBarView : LeftBarView?

override func loadView() {
    leftBarView = LeftBarView(frame: NSZeroRect)
    view = leftBarView!
}

func setup(title : String){

    leftBarView?.titleTextView.string = title
}

}

在左栏视图中

class LeftBarView: NSView {

lazy var titleTextView : NSTextView = {

    let titleTextView = NSTextView()

    titleTextView.isEditable = false
    titleTextView.isSelectable = false
    titleTextView.font = NSFont(name: "Helvetica", size: 20)
    return titleTextView
}()

override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)

    self.setupViews()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
}

func setupViews(){
    self.addSubview(titleTextView)

    self.wantsLayer = true
    self.layer?.backgroundColor = NSColor.lightGray.cgColor

    titleTextView <- Edges()
}

}

我试过

    self.leftBar.isSelectable = true
    leftBar.allowsMultipleSelection = true

并且可以进行多项选择。 来自 NSCollectionViewDelegatedidSelectItemsAt 被触发

但是当我尝试使用这个

    self.leftBar.isSelectable = true

    self.leftBar.isSelectable = true
    self.leftBar.allowsEmptySelection = true

当我点击collectionviewitem时它不起作用, 来自 NSCollectionViewDelegatedidSelectItemsAt 未被触发。

如有任何想法,我们将不胜感激!

已解决。这是因为textview覆盖了单元格,你可能需要禁用textview变成被动的。

extension NSTextView {

 open override func hitTest(_ point: NSPoint) -> NSView? {
    return nil
   }
}