ehmunnehm ehmunnehm - 3 months ago 39
Swift Question

NSTableView grouping

I am trying to add groups to my NSTableView. I found this function:

func tableView(tableView: NSTableView, isGroupRow row: Int) -> Bool
{
if (row == 5)
{
return true;
}

return false;
}


Which works great. Row 5 is a group after that. But I am not sure how to add a title to that?

I am using a custom view:

func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
if (row == 5)
{
??????
}

let result : CellViewCustom = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! CellViewCustom

...

return result
}


But in row 5 it says tableColumn == nil

How do I add text to the group header?

Answer

Unlike in iOS, the group cells of NSTableView are "inline" in the (non-nested) data source array.

Simple example

  • A custom struct Item with property name, title and isGroup. All instances whose title is not empty are group rows

    struct Item {
    
      let name, title : String
      let isGroup : Bool
    
      init(name : String, title : String = "") {
        self.name = name
        self.title = title
        self.isGroup = !title.isEmpty
      }
    }
    
  • Create a data source array and assign 2 group and 3 normal rows

    var items = [Item]()
    
    ...
    
    items = [Item(name:"", title:"Group 1"), 
             Item(name:"bar"), 
             Item(name:"baz"), 
             Item(name:"", title:"Group 2"), 
             Item(name:"zab")]
    
  • In isGroupRow just return the value of the property

    func tableView(tableView: NSTableView, isGroupRow row: Int) -> Bool
    {
      return items[row].isGroup
    }
    
  • In viewForTableColumn create two different views for group and table row

    func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
    {
      let item = items[row]
      if item.isGroup {
        let groupCell = tableView.makeViewWithIdentifier("GroupCell", owner:self) as! NSTableCellView
        groupCell.textField!.stringValue = item.title
        return cell
      } else {
        let cell = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! CellViewCustom
    
        ...
    
        return cell
      }
    }
    
Comments