Coloring rows in View based NSTableview

后端 未结 4 1523
清酒与你
清酒与你 2021-02-12 17:26

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 *)         


        
4条回答
  •  不知归路
    2021-02-12 18:33

    For anyone else who hits this and wants a custom NSTableRowView backgroundColor, there are two approaches.

    1. 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];
      
      }
      
    2. 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;
      }
      

提交回复
热议问题