onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
680 stars 33 forks source link

How to highlight selection of NSCollectionViewItem #296

Open onmyway133 opened 5 years ago

onmyway133 commented 5 years ago

Original answer https://stackoverflow.com/a/54793979/1418457


In your NSCollectionViewItem subclass, override isSelected and change background color of the layer. Test in macOS 10.14 and Swift 4.2

class Cell: NSCollectionViewItem {

  override func loadView() {    
    self.view = NSView()
    self.view.wantsLayer = true
  }

  override var isSelected: Bool {
    didSet {
      self.view.layer?.backgroundColor = isSelected ? NSColor.gray.cgColor : NSColor.clear.cgColor
    }
  }
}
FledgeXu commented 4 months ago

Great article! Just save my ass!