-->

NSCollectionView selection handling in Swift

2019-06-24 06:27发布

问题:

Learning with Swift and I've been at this all day with little progress:

Need to know when an item in NSCollectionView is selected. The end goal is to get the item to highlight and to be able to delete it from the collection with the delete key. My NSCollectionView is bound to an ArrayController to get content and send the selection indexes, so looks like I need to be watching the ArrayController for a selection change, but don't see any helpful delegate methods there. The prototype view has a single textfield.

I was following the obj-c examples here and elsewhere (found none in Swift), but a Swift NSCollectionViewItem doesn't have the setSelected method to override. It has a selected property.

How to get informed when an NSCollectionViewItem gets selected in Swift?

回答1:

The most simple solution is to override the selected property and react for example whenever it is set:

class CollectionSonaViewItem: NSCollectionViewItem {
  override var isSelected: Bool {
    didSet {
      // set background color to indicate selection
      self.view.layer?.backgroundColor = (isSelected ? NSColor.blue.cgColor : NSColor.clear.cgColor)
      // do more stuff
    }
  }

From there on you can send a notification or call a function in your collection view class, its delegate or whatever required.