Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save kopyl/12f1d7bf63f6128a444917e33dd6daec to your computer and use it in GitHub Desktop.

Select an option

Save kopyl/12f1d7bf63f6128a444917e33dd6daec to your computer and use it in GitHub Desktop.
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