Search code examples
macosnstableviewnstablecellview

NSTableView with two custom table cell views alternating per row (MacOS)


I have a single column, view-based NSTableView in which I want to place two different custom cell views, one alternating with the other in each row, like so:

Odd rows: OddRowNumberCellView. Even rows: EvenRowNumberCellView.

There a solution for iOS from Natasha in her highly rated answer UITableview with more than One Custom Cells with Swift but it depends on the Dynamic Prototypes setting in the Attributes Inspector, a feature that is not available for MacOS.

Does anyone know how to do this on Mac please? (I'm on macOS Sierra 10.12.4.)


Solution

  • You do exactly the same but instead of Dynamic Protoypes you set an Identifier "OddRow" or "EvenRow" and then in your datasource implementation:

    if indexPath.row % 2 == 0 {
       let cellView: tableView.make(withIdentifier: "EvenRow")
       //set the data here
       return cellView
    } else {
       let cellView: tableView.make(withIdentifier: "OddRow")
       //set the data here
       return cellView
    }