I have a view based nstableview. I want to color entire row based on some condtion for which I have used code below
- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
NSTableRowView *view = [[NSTableRowView alloc] initWithFrame:NSMakeRect(1, 1, 100, 50)];
[view setBackgroundColor:[NSColor redColor]];
return view;;
}
The delegate method is called, but table doesn't seem to be using NSTableRowView
returned by delegate method.
Main aim here is coloring entire row based on some condition. Whats wrong in above implementation?
For anyone else who hits this and wants a custom NSTableRowView backgroundColor, there are two approaches.
If you don't need custom drawing, simply set rowView.backgroundColor
in - (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
in your NSTableViewDelegate
.
Example:
- (void)tableView:(NSTableView *)tableView
didAddRowView:(NSTableRowView *)rowView
forRow:(NSInteger)row {
rowView.backgroundColor = [NSColor redColor];
}
If you do need custom drawing, create your own NSTableRowView
subclass with desired drawRect
. Then, implement the following in NSTableViewDelegate
:
Example:
- (NSTableRowView *)tableView:(NSTableView *)tableView
rowViewForRow:(NSInteger)row {
static NSString* const kRowIdentifier = @"RowView";
MyRowViewSubclass* rowView = [tableView makeViewWithIdentifier:kRowIdentifier owner:self];
if (!rowView) {
// Size doesn't matter, the table will set it
rowView = [[[MyRowViewSubclass alloc] initWithFrame:NSZeroRect] autorelease];
// This seemingly magical line enables your view to be found
// next time "makeViewWithIdentifier" is called.
rowView.identifier = kRowIdentifier;
}
// Can customize properties here. Note that customizing
// 'backgroundColor' isn't going to work at this point since the table
// will reset it later. Use 'didAddRow' to customize if desired.
return rowView;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With