Coloring NSTableView Text per row

允我心安 提交于 2019-12-21 05:11:09

问题


I have a NSTableView that is displaying an array of objects I have. For each of these objects (rows) I would like to change the color of the text displayed depending on the results of a function I run on each object;

So for example all the object in the table that exist in another list (or some other requirement) I want to display them in green text, and objects that don't exist display in red.

How would I go about doing this?


回答1:


Assuming that you have NSTextFieldCell in your table (for other cells, setting text color may vary), you can achieve this by implementing a NSTableView's delegate method.

First, you have to define a delegate for the NSTableView, either in Interface Builder or in your code. This can be your application controller for example.

Then, just implement the following method:

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
    NSTextFieldCell *cell = aCell;
    if (...) {
        [cell setTextColor:[NSColor greenColor]];
    } else if (...) {
        [cell setTextColor:[NSColor redColor]];
    } else {
        [cell setTextColor:[NSColor blackColor]];
    }
}

Each time the NSTableView will draw a cell, you have the opportunity to modify it before it get drawn.

Check out the NSTableViewDelegate documentation page for more details.



来源:https://stackoverflow.com/questions/2786362/coloring-nstableview-text-per-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!