Search code examples
swiftmacosnstableview

Selecting a row in a NSTableView (Swift)


I want my Mac App to do something when a row in my table view is selected. In iOS, I could use didSelectRowAt to do something when a table view cell was tapped:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Some code
}

In iOS, when a table view cell was tapped, didSelectRowAt would be executed. How do you do something like this with NSTableView in macOS?


Solution

  • There are two options:

    1. Implement tableViewSelectionDidChange(_:) of NSTableViewDelegate and check selectedRow or selectedRowIndexes
    2. Use Cocoa Bindings: Bind selectionIndexes of the table view to a dynamic var of type IndexSet and use the didSet observer.