如何更改NSOutlineView的每个单元格的颜色或NSTableCellView

时间:2013-08-07 21:00:34

标签: objective-c cocoa

我查看了一些问题,但找不到基于视图的NSOutlineView的良好解决方案

Coloring NSTableView Text per row

Change color of NSTableViewCell

Custom background colors for NSTableCellView

我正在尝试将每一行设置为我想要的任何颜色。我已经读过一些我需要继承NSTableRowView的地方,我现在已经完成了。

根据AppleDocs,我看到以下方法:

– drawBackgroundInRect:
– drawDraggingDestinationFeedbackInRect:
– drawSelectionInRect:
– drawSeparatorInRect:

我如何设置各行的背景颜色?我上面的路线走错了吗?

编辑:下方(也是已修改的标题)

由于我使用的是NSOutlineView而不是NSTableView,当我更改单元格的背景颜色时,图像如下所示。左边的公开箭头没有着色。有没有办法改变NSOutlineView的整行颜色?

this

3 个答案:

答案 0 :(得分:1)

您可以继承NSTableViewCell,并为其添加一个设置其颜色的方法。

NSTableViewCell已经是NSView的子类,因此在您的子类中,您将添加以下方法:

- (void)setBackgroundColor {
    self.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 1.0f); // or whatever color
}

或类似的东西。您可能希望将颜色作为方法的参数。然后,在表视图委托中,您可以根据传递给委托方法的行索引设置颜色。例如:

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

    if (indexPath.row % 2) {
        [cell setBackgroundColor:[UIColor redColor]]; // or something like that
    }
}

答案 1 :(得分:1)

想出一个解决方案。实现了以下内容。

-(void)outlineView:(NSOutlineView *)outlineView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row {
    [self updateRowViewBackColorforItem:[outlineView itemAtRow:row]];
}

-(void)updateRowViewBackColorforStep:(myCustomItem *)customItem {
    static NSColor *color1;
    static NSColor *color2;
    static NSColor *color3;

    if (color1 == nil) {
        sharedcolorHeader = [NSColor colorWithCalibratedRed:(r/255.0f) green:(g/255.0f) blue:(b/255.0f) alpha:1.0];
    }
    if (color2 == nil) {
        sharedcolorChildren = [NSColor colorWithCalibratedRed:(x/255.0f) green:(y/255.0f) blue:(z/255.0f) alpha:1.0];
    }
    if (color3 == nil) {
        normalColor = [NSColor colorWithCalibratedRed:(255/255.0f) green:(255/255.0f) blue:(255/255.0f) alpha:1.0];
    }

    NSInteger row = [stepOutlineView rowForItem:step];
    if (row < 0) return;

    NSTableRowView *view = [myOutlineView rowViewAtRow:row makeIfNecessary:NO];

   if ([customItem type] == 1) {
        [view setBackgroundColor:sharedcolorHeader];
    } else if([customItem type] == 2) {
        [view setBackgroundColor:sharedcolorChildren];
    } else {
        [view setBackgroundColor:normalColor];
    }
}

答案 2 :(得分:0)

这确实应该依赖于数据模型中的属性或ivars。 如果使用基于视图的大纲视图,则可以只为行视图和/或单元视图提供自定义视图。 让自定义视图根据所表示对象中的数据绘制您想要的任何内容。