How to customize a table item content on selection and on emphasis change for a NSTableView?

162 views Asked by At

I'm currently trying to create a 3-pane layout in SwiftUI. Since SwiftUI's List doesn't provide greater customisation, I decided to create my own NSViewRepresentableView based on NSTableView. The NSTableView has a single column and each row is represented by a NSHostingView that contains a SwiftUI View. Here's a partial screenshot of how it looks with a single item selected:

enter image description here

I have two questions:

  1. The text should be white color when an item is selected. How do I do this? I have solved this part with tableViewSelectionDidChange() and messing up views, but it has very slow performance and looks like a mess.
  2. When the tableview with some selection loses focus, how do I detect that and go back to black color again?

enter image description here

Here's the code I've written so far:

struct MkList<Data, RowContent> : NSViewRepresentable where Data : RandomAccessCollection, RowContent : View {
    var data: Data
    var rowContent: (Data.Element) -> RowContent
    
    public init(_ data: Data, @ViewBuilder rowContent: @escaping (Data.Element) -> RowContent) {
        self.data = data
        self.rowContent = rowContent
    }
    
    final class Coordinator: NSObject, NSTableViewDelegate, NSTableViewDataSource {
        
        var parent: MkList<Data, RowContent>
        
        init(_ parent: MkList<Data, RowContent>) {
            self.parent = parent
        }
        
        func numberOfRows(in tableView: NSTableView) -> Int {
            return parent.data.count
        }
        
        func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
            50
        }
        
        func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
            let x = NSHostingView(rootView: parent.rowContent(parent.data[parent.data.index(parent.data.startIndex, offsetBy: row)], row).foregroundColor(.primary))
            return x
        }
        
        func tableViewSelectionDidChange(_ notification: Notification) {
            let tableView = notification.object as! NSTableView
            parent.selection = Set(tableView.selectedRowIndexes.map({ $0 }))
            for row in 0..<parent.data.count {
                let v: NSHostingView<ModifiedContent<RowContent, _EnvironmentKeyWritingModifier<Color?>>> = tableView.view(atColumn: 0, row: row, makeIfNecessary: true) as! NSHostingView<ModifiedContent<RowContent, _EnvironmentKeyWritingModifier<Color?>>>
                v.rootView = parent.rowContent(parent.data[parent.data.index(parent.data.startIndex, offsetBy: row)], row).foregroundColor(parent.selection.contains(row) ? .white : .primary) as! ModifiedContent<RowContent, _EnvironmentKeyWritingModifier<Color?>>
            }
        }
        
    }
    
    func makeNSView(context: Context) -> NSScrollView {
        let tableView = NSTableView()
        tableView.delegate = context.coordinator
        tableView.dataSource = context.coordinator
        tableView.allowsMultipleSelection = true
        tableView.headerView = nil
        tableView.selectionHighlightStyle = .regular
        tableView.gridStyleMask = NSTableView.GridLineStyle.solidHorizontalGridLineMask
        let col = NSTableColumn()
        col.minWidth = 250
        tableView.addTableColumn(col)
        
        let scrollView = NSScrollView()
        scrollView.documentView = tableView
        scrollView.hasVerticalScroller = true
        scrollView.autohidesScrollers = true
        return scrollView
    }
    
    func updateNSView(_ nsView: NSScrollView, context: Context) {
        print("Update table called")
        let tableView = (nsView.documentView as! NSTableView)
        context.coordinator.parent = self
        print(data)
        // actually, model should tell us if reload is needed or not
        tableView.reloadData()
        // ... some basic logic to keep selection state ...
        
    }
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }
}

The MkList View is used as follows:

struct DownloadsView: View {
    // The downloads will be retrieved and updated here only
    @State var downloadsList: [String] = ["Download 1", "Download 2", "Download 3"]
    
    var body: some View {
        MkList(downloadsList) { i in
            DownloadListItemView(downloadName: i)
        }
    }
    
}

Overall, what is the best approach to solve this problem?

0

There are 0 answers