Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of NSTableViewCell

How can I change the color of a cell in my NSTableView?

like image 403
Matt S. Avatar asked May 21 '10 02:05

Matt S.


2 Answers

In your NSTableViewDelegate for the NSTableView, implement this method:

- (void)tableView:(NSTableView *)tableView 
  willDisplayCell:(id)cell 
   forTableColumn:(NSTableColumn *)tableColumn 
              row:(NSInteger)row

The NSTableView calls this on its delegate before displaying each cell so that you can affect its appearance. Assuming you're using NSTextFieldCells, for the cell that you want to change call:

[cell setBackgroundColor:...];

Or, if you want to change the text color:

[cell setTextColor:...];

If you want columns to have different appearances, or if all of the columns aren't NSTextFieldCells, use [tableColumn identifier] to, er, identify the column. You can set the identifier in Interface Builder by selecting the table column.

like image 157
Adam Preble Avatar answered Sep 23 '22 01:09

Adam Preble


// TESTED - Swift 3 solution...for changing color of cell text in a single column. All columns in my tableview have a unique identifier

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

        let myCell:NSTableCellView = tableView.make(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView
        if tableColumn?.identifier == "MyColumn" {
            let results = arrayController.arrangedObjects as! [ProjectData]
            let result = results[row]
            if result.ebit < 0.0 {
                myCell.textField?.textColor = NSColor.red
            } else {
                myCell.textField?.textColor = NSColor.black
            }
        }
        return myCell
    }
like image 26
John Carto Avatar answered Sep 23 '22 01:09

John Carto