2012-02-05 37 views
4

我有一个基于NSTableView的视图,带有一个自定义的NSTableCellView。这个自定义的NSTableCellView有几个标签(NSTextField)。 NSTableCellView的整个UI都是在IB中构建的。NSTableCellView中的NSTextField

NSTableCellView可以处于正常状态并处于选定状态。在正常状态下,所有文本标签都应该是黑色的,在选定状态下它们应该是白色的。

我该如何管理?

回答

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; 
    } 
} 

然后得出这样的观点:

if (selected) { 
    // set your color here 
    // draw [self stringValue] here in [self bounds] 
} else { 
    // call [super drawRect] 
} 
+0

非常感谢... – burki 2012-02-11 18:48:43

+0

Seth的建议的方法是正确的做法,应该被标记为正确的答案。上面的方法是错误的,它会对滚动/绘图性能产生影响 – strange 2012-05-31 22:13:16

+1

不幸的是,Seth的解决方案仅适用于“源列表”风格的表视图。在标准样式的表格视图中,只有蓝色选定状态是NSBackgroundStyleDark。如果一个项目被选中,但表格视图不是第一个响应者,你会得到一个灰色的行高亮,这是NSBackgroundStyleLight ... – 2012-12-28 06:49:37

14

覆盖setBackgroundStyle:在NSTableCellView知道当背景,这种变化是什么影响了什么文字的颜色,你应该在你的使用。

例如:

- (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; 
    } 
} 

在源列表表视图单元格视图的背景样式设置为轻,这是它的文本框的backgroundStyle,但文本字段也借鉴了一层阴影其文本之下,还没有发现究竟是什么控制/确定它应该发生。

+0

感谢你!但是这对组行不起作用... – NSAddict 2013-03-07 22:59:16

0

这工作不管表视图有什么样的风格:

- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle { 
    [super setBackgroundStyle:backgroundStyle]; 
    NSTableView *tableView = self.enclosingScrollView.documentView; 
    BOOL tableViewIsFirstResponder = [tableView isEqual:[self.window firstResponder]]; 
    NSColor *color = nil; 
    if(backgroundStyle == NSBackgroundStyleLight) { 
     color = tableViewIsFirstResponder ? [NSColor lightGrayColor] : [NSColor darkGrayColor]; 
    } else { 
     color = [NSColor whiteColor]; 
    } 
    myTextField.textColor = color; 
}