NSTextField在NSTableCellView中

bur*_*rki 5 macos cocoa nstextfield nstableview

我有一个基于NSTableView的视图与自定义NSTableCellView.此自定义NSTableCellView具有多个标签(NSTextField).NSTableCellView的整个UI都是在IB中构建的.

NSTableCellView可以处于正常状态并处于选定状态.在正常状态下,所有文本标签应为黑色,在选定状态下,它们应为白色.

我该怎么办呢?

小智 14

覆盖NSTableCellView上的setBackgroundStyle:以了解背景何时发生变化,这会影响您在单元格中应使用的文本颜色.

例如:

- (void)setBackgroundStyle:(NSBackgroundStyle)style
{
    [super setBackgroundStyle:style];

    // If the cell's text color is black, this sets it to white
    [((NSCell *)self.descriptionField.cell) setBackgroundStyle:style];

    // Otherwise you need to change the color manually
    switch (style) {
        case NSBackgroundStyleLight:
            [self.descriptionField setTextColor:[NSColor colorWithCalibratedWhite:0.4 alpha:1.0]];
            break;

        case NSBackgroundStyleDark:
        default:
            [self.descriptionField setTextColor:[NSColor colorWithCalibratedWhite:1.0 alpha:1.0]];
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

在源列表表视图中,单元格视图的背景样式设置为Light,其textField的backgroundStyle也是如此,但textField还在其文本下绘制阴影,但尚未找到控制它的确切内容/确定它应该发生的情况.


Tim*_*Tim 0

完成此操作的最简单方法可能是子类化 NSTextField 并重写子类中的 drawRect: 方法。在那里,您可以使用以下代码确定当前是否选择了包含 NSTextField 实例的 NSTableCellView 实例(我将其与 NSOutlineView 一起使用,但它也应该与 NSTableView 一起使用):

BOOL selected = NO;
id tableView = [[[self superview] superview] superview];
if ([tableView isKindOfClass:[NSTableView class]]) {
    NSInteger row = [tableView selectedRow];
    if (row != -1) {
        id cellView = [tableView viewAtColumn:0 row:row makeIfNecessary:YES];
        if ([cellView isEqualTo:[self superview]]) selected = YES;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样绘制视图:

if (selected) {
    // set your color here
    // draw [self stringValue] here in [self bounds]
} else {
    // call [super drawRect]
}
Run Code Online (Sandbox Code Playgroud)