首页 > 解决方案 > 如何在 NSTableView 的选择和重点更改上自定义表格项目内容?

问题描述

我目前正在尝试在 SwiftUI 中创建一个 3 窗格布局。由于 SwiftUI 的 List 没有提供更多的自定义功能,我决定基于 NSTableView 创建自己的 NSViewRepresentableView。NSTableView 有一个列,每一行都由一个包含 SwiftUI 视图的 NSHostingView 表示。这是选择单个项目后的部分屏幕截图:

在此处输入图像描述

我有两个问题:

  1. 选择项目时,文本应为白色。我该怎么做呢?我已经用 tableViewSelectionDidChange() 解决了这部分并弄乱了视图,但是它的性能非常慢并且看起来一团糟。
  2. 当带有某些选择的表格视图失去焦点时,我如何检测到它并再次返回黑色?

在此处输入图像描述

这是我到目前为止编写的代码:

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)
    }
}

视图使用MkList如下:

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)
        }
    }
    
}

总的来说,解决这个问题的最佳方法是什么?

标签: swiftswiftuinstableviewappkitnsviewrepresentable

解决方案


推荐阅读