Chang text colour for complete row in NSTableView based on value

Hi,


I am looking for a way to change the text color for all cells in a row to red if the value of a certain value in that row is < 0.

I am using a NSTableView, an Array Controller and Bindings to populate the table.


Any ideas?


Max

Answered by bobandsee in 257162022

Founds this one and it seems to do the trick 🙂


func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  if let myCell:NSTableCellView = tableView.make(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView {
  let value = transactions[row].amount

  if (value >= 0) {
  myCell.textField?.textColor = NSColor.green
  } else {
  myCell.textField?.textColor = NSColor.red
  }
  return myCell
  }
  }


Source: https://stackoverflow.com/a/42880412/6713399

I did this (OSX App), to have cell in blue or magenta depending on some condition of the cell.


Implement the selection of color in In the delegate func doing like this:


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

               let p = contentOfRow[row]          // get the textField content from the dataSource
               let value = valueForTesting[row]     // to know if cell must be red or blue
                if let cellView = tableView.make(withIdentifier: "MyCell", owner: self) {
                    (cellView as! NSTableCellView).textField?.stringValue = p
                    if value >= 0 {       
                        (cellView as! NSTableCellView).textField?.textColor = NSColor.blue
                    } else { 
                        (cellView as! NSTableCellView).textField?.textColor = NSColor.red
                    }
                    return cellView
                } else {
                    return nil
                }
}

Hm, ok that makes the whole line read but if I have 5 columns, do I have to specify for each NSTableCellView an identifier to populate the proper value from my object like


contentOfRow[row].name
contentOfRow[row].amount
contentOfRow[row].date


and then repeat the


if let cellView = tableView.make(withIdentifier: "MyCell", owner: self) {


for every case?

Accepted Answer

Founds this one and it seems to do the trick 🙂


func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
  if let myCell:NSTableCellView = tableView.make(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView {
  let value = transactions[row].amount

  if (value >= 0) {
  myCell.textField?.textColor = NSColor.green
  } else {
  myCell.textField?.textColor = NSColor.red
  }
  return myCell
  }
  }


Source: https://stackoverflow.com/a/42880412/6713399

Great you have found a solution. Your original post did not tell it was multicolumn and you needed to change all coloumns color.

Chang text colour for complete row in NSTableView based on value
 
 
Q