简体   繁体   中英

NSCollectionView selection handling in Swift

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM