NSCollectionView selection handling in Swift

让人想犯罪 __ 提交于 2019-12-12 12:21:57

问题


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.



来源:https://stackoverflow.com/questions/28250147/nscollectionview-selection-handling-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!