0

I am trying to create an NSTableView with dynamic content, rows and columns. And I am creating columns dynamically with the data array like

private func addHeader() {
    self.dbTableView.tableColumns.forEach { self.dbTableView.removeTableColumn($0)}
    for  column in table!.columnNames {
        let tableColumn = NSTableColumn()
        tableColumn.headerCell.title = column
        tableColumn.headerCell.alignment = .center
        tableColumn.identifier = NSUserInterfaceItemIdentifier(rawValue: column)

        self.dbTableView.addTableColumn(tableColumn)
    }
}

And I have override the delegate method

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

    guard let vw = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as? NSTableCellView else { return nil }

    for i in 0..<table!.columnCount {
        let columnName = table?.columnNames[i]
        let data = table?.rows[row][i]

        if tableColumn!.identifier.rawValue == columnName {
            vw.textField?.stringValue = data ?? ""
        }
    }
    return vw
}

But the makeView(withIdentifier:, owner:) returns nil always.

I have tried below delegate but it did not fire.

 func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
    for i in 0..<table!.columnCount {
        let columnName = table?.columnNames[i]
        let data = table?.rows[row][i]

        if tableColumn!.identifier.rawValue == columnName {
            return data
        }
    }
    return ""
}

How to resolve this issue?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
noobEinstien
  • 3,147
  • 4
  • 24
  • 42
  • Please read the documentation of `makeView(withIdentifier:owner:)`. `tableView(_:objectValueFor:row:)` is a `NSTableViewDataSource` method. – Willeke Jun 13 '19 at 12:21
  • If your datasource class implements `viewForTableColumn` then `objectValueForTableColumn` would not be used(called) by `NSTableVIew`. – Bharat Gadde Jun 17 '19 at 07:14
  • Your tableView did'nt registered the nib to create a view when `makeViewWithIdentifier` is called. Register a nib with the identifier and it will not return nil. – Bharat Gadde Jun 17 '19 at 07:19
  • @BharatKumar `objectValueForTableColumn` is called when `viewForTableColumn` is implemented. – Willeke Jun 21 '19 at 08:14

0 Answers0