Created
March 20, 2025 15:47
-
-
Save kopyl/12f1d7bf63f6128a444917e33dd6daec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| struct NSTableViewWrapper: NSViewRepresentable { | |
| class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate { | |
| var parent: NSTableViewWrapper | |
| init(parent: NSTableViewWrapper) { | |
| self.parent = parent | |
| } | |
| func numberOfRows(in tableView: NSTableView) -> Int { 1 } | |
| func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { | |
| let rowView = NSTableRowView() | |
| let textField = NSTextField(labelWithString: "Item") | |
| textField.isEditable = false | |
| textField.isBordered = false | |
| textField.backgroundColor = .clear | |
| textField.drawsBackground = false | |
| rowView.addSubview(textField) | |
| tableView.selectionHighlightStyle = .none | |
| return rowView | |
| } | |
| func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] { | |
| return [NSTableViewRowAction(style: .destructive, title: "Delete") { _, _ in }] | |
| } | |
| func tableViewSelectionDidChange(_ notification: Notification) { | |
| guard let tableView = notification.object as? NSTableView else { return } | |
| guard tableView.selectedRow >= 0 else { | |
| for i in 0..<tableView.numberOfRows { | |
| guard let rowView = tableView.rowView(atRow: i, makeIfNecessary: false) else { | |
| return | |
| } | |
| rowView.backgroundColor = .clear | |
| } | |
| return | |
| } | |
| guard let rowView = tableView.rowView(atRow: tableView.selectedRow, makeIfNecessary: false) else { | |
| return | |
| } | |
| rowView.backgroundColor = .red.withAlphaComponent(0.1) | |
| } | |
| } | |
| func makeCoordinator() -> Coordinator { | |
| return Coordinator(parent: self) | |
| } | |
| func makeNSView(context: Context) -> NSScrollView { | |
| let scrollView = NSScrollView() | |
| let tableView = NSTableView() | |
| let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Column")) | |
| tableView.addTableColumn(column) | |
| tableView.delegate = context.coordinator | |
| tableView.dataSource = context.coordinator | |
| scrollView.documentView = tableView | |
| return scrollView | |
| } | |
| func updateNSView(_ nsView: NSScrollView, context: Context) { | |
| (nsView.documentView as? NSTableView)?.reloadData() | |
| } | |
| } | |
| struct ContentView: View { | |
| var body: some View { | |
| NSTableViewWrapper() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment