Has anyone gotten NSTableView
to work with SwiftUI? Whenever I run my code my app will not load but there are also no errors. There aren't any examples for tableviews but I thought it would be using the NSViewControllerRepresentable
. I'm not entirely sure how you style the table and add it to the view. Thank you for the help!
struct SampleViewController: NSViewControllerRepresentable {
var tableView:NSTableView = {
let table = NSTableView(frame: .zero)
table.rowSizeStyle = .large
table.backgroundColor = .clear
return table
}()
func makeNSViewController(context: Context) -> NSViewController {
return NSViewController()
}
func updateNSViewController(_ nsViewController: NSViewController, context: Context) {
//tbd
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
var parent: SampleViewController
init(_ tvController: SampleViewController) {
self.parent = tvController
}
func numberOfRows(in tableView: NSTableView) -> Int {
return 10
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
return nil
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return CGFloat(90)
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return false
}
}
}
struct SampleView: View {
var body: some View {
SampleViewController()
}
}
I have a feeling you might have figured this one out, but you haven't actually set the tableView
property as the view
of your view controller. So, when presented, your SwiftUI view is just going to be backed by a plain NSView
.
In this particular example, I think an NSViewRepresentable
would probably be nicer, since your controller has no logic anyways.
Just in case this is helpful, another thing to keep in mind is the role of the coordinator and its relationship to the parent
property. Because the coordinator is created and reused, its parent
is not updated if the SwiftUI view is re-created. This really tripped me up as I tried to reload table data in func updateNSViewController(_ nsViewController: NSViewController, context: Context)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With