在基于视图的NSTableview中着色行

sac*_*ach 18 cocoa nstableview

我有一个基于nstableview的视图.我想根据我使用下面代码的一些条件为整行着色

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row 
{
    NSTableRowView *view = [[NSTableRowView alloc] initWithFrame:NSMakeRect(1, 1, 100, 50)];

    [view setBackgroundColor:[NSColor redColor]];
    return view;;
}
Run Code Online (Sandbox Code Playgroud)

调用委托方法,但表似乎没有使用NSTableRowView委托方法返回的表.

这里的主要目的是根据某些条件着色整行.以上实施有什么不对?

DPl*_*usV 37

对于其他人来说,并且想要一个自定义的NSTableRowView backgroundColor,有两种方法.

  1. 如果你不需要自定义绘制,只需设置rowView.backgroundColor- (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row你的NSTableViewDelegate.

    例:

    - (void)tableView:(NSTableView *)tableView
        didAddRowView:(NSTableRowView *)rowView
               forRow:(NSInteger)row {
    
        rowView.backgroundColor = [NSColor redColor];
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果确实需要自定义绘图,请根据需要创建自己的NSTableRowView子类drawRect.然后,实现以下内容NSTableViewDelegate:

    例:

    - (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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这非常有效.在我发现这个之前,我对如何添加我的子类行感到有些困惑,但这会产生奇迹. (2认同)

Mon*_*olo 0

如果您观看 WWDC 2011 上有关基于视图的表视图的演示,您会发现主要思想是在 Interface Builder 中创建视图,然后从那里获取它们。就像是:

[tableView makeViewWithIdentifier:@"GroupRow" owner:self];
Run Code Online (Sandbox Code Playgroud)

获得视图后,只需设置其属性并返回即可。

请注意,在此示例中,它有自己的标识符,因此请记住进行设置,但您也可以使用自动标识符。

我不知道 WWDC 的直接链接是否有效,但主页在这里: https: //developer.apple.com/videos/wwdc/2011/如果您搜索“View Based NSTableView Basic to Advanced” ”,你会找到的。非常值得一看。