|
5 | 5 |
|
6 | 6 | import AppKit |
7 | 7 |
|
8 | | -/// Custom cell view that draws change-state backgrounds via `draw(_:)` instead |
9 | | -/// of `layer.backgroundColor`. AppKit's `NSTableRowView` sets `backgroundStyle` |
10 | | -/// to `.emphasized` when the row is selected — we skip the custom background in |
11 | | -/// that case so the native selection highlight shows through. |
| 8 | +/// Custom cell view that uses a background subview for change-state coloring. |
| 9 | +/// AppKit's `NSTableRowView` sets `backgroundStyle` to `.emphasized` when the |
| 10 | +/// row is selected — we hide the background view so the native selection highlight |
| 11 | +/// shows through. |
12 | 12 | final class DataGridCellView: NSTableCellView { |
13 | | - var changeBackgroundColor: NSColor? |
| 13 | + private lazy var backgroundView: NSView = { |
| 14 | + let view = NSView() |
| 15 | + view.wantsLayer = true |
| 16 | + view.translatesAutoresizingMaskIntoConstraints = false |
| 17 | + addSubview(view, positioned: .below, relativeTo: subviews.first) |
| 18 | + NSLayoutConstraint.activate([ |
| 19 | + view.leadingAnchor.constraint(equalTo: leadingAnchor), |
| 20 | + view.trailingAnchor.constraint(equalTo: trailingAnchor), |
| 21 | + view.topAnchor.constraint(equalTo: topAnchor), |
| 22 | + view.bottomAnchor.constraint(equalTo: bottomAnchor), |
| 23 | + ]) |
| 24 | + return view |
| 25 | + }() |
14 | 26 |
|
15 | | - override var backgroundStyle: NSView.BackgroundStyle { |
16 | | - didSet { needsDisplay = true } |
| 27 | + var changeBackgroundColor: NSColor? { |
| 28 | + didSet { |
| 29 | + if let color = changeBackgroundColor { |
| 30 | + backgroundView.layer?.backgroundColor = color.cgColor |
| 31 | + backgroundView.isHidden = (backgroundStyle == .emphasized) |
| 32 | + } else { |
| 33 | + backgroundView.layer?.backgroundColor = nil |
| 34 | + backgroundView.isHidden = true |
| 35 | + } |
| 36 | + } |
17 | 37 | } |
18 | 38 |
|
19 | | - override func draw(_ dirtyRect: NSRect) { |
20 | | - if backgroundStyle != .emphasized, let color = changeBackgroundColor { |
21 | | - color.setFill() |
22 | | - dirtyRect.fill() |
| 39 | + override var backgroundStyle: NSView.BackgroundStyle { |
| 40 | + didSet { |
| 41 | + backgroundView.isHidden = (backgroundStyle == .emphasized) || (changeBackgroundColor == nil) |
23 | 42 | } |
24 | | - super.draw(dirtyRect) |
25 | 43 | } |
26 | 44 | } |
0 commit comments