NSTableView 选中行背景色

NSTableView默认 NSTableViewSelectionHighlightStyle

NSTableview有三种选中模式

typedef NS_ENUM(NSInteger, NSTableViewSelectionHighlightStyle) {
 
    NSTableViewSelectionHighlightStyleNone NS_ENUM_AVAILABLE_MAC(10_6) = -1,
    
    NSTableViewSelectionHighlightStyleRegular = 0,
    
    NSTableViewSelectionHighlightStyleSourceList = 1,

默认模式为NSTableViewSelectionHighlightStyleRegular在此种模式下,行选中颜色有light blue ([NSColor alternateSelectedControlColor]) 和 light gray color ([NSColor secondarySelectedControlColor])两种。
在开发过程中,根据需求会有改变选中状态下行背景色的情况。下面为将介绍两种改变背景色的方法。

  • 继承NSTableRowView

    继承NSTableRowView ,重写- (void)drawSelectionInRect:(NSRect)dirtyRect 方法。

  - (void)drawSelectionInRect:(NSRect)dirtyRect {
    if (self.selectionHighlightStyle != NSTableViewSelectionHighlightStyleNone) {
        NSRect selectionRect = NSInsetRect(self.bounds, 0, 0);
        [[NSColor yellowColor] setFill];
        NSBezierPath *selectionPath = [NSBezierPath bezierPathWithRoundedRect:selectionRect xRadius:0 yRadius:0];
        [selectionPath fill];
    }
}

实现协议NSTableViewDelegate的- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row方法

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
    YLTableRowView *rowView = [[YLTableRowView alloc] init];
    return rowView;
}
  • 继承NSTableCellView, 重写- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle方法cellView的backgroudStyle由NSTableRowView自动设置,可根据backgroudStyle的类型对cellView的背景色进行控制。

The backgroundStyle property is automatically set by the enclosing NSTableRowView to let this view know what its background looks like. For instance, when the -backgroundStyle is NSBackgroundStyleDark, the view should use a light text color.

- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle
{
    [super setBackgroundStyle:backgroundStyle];
    if(backgroundStyle == NSBackgroundStyleDark)
    {
        self.backgroundColor = [NSColor yellowColor];
    }
    else
    {
        self.backgroundColor = [NSColor whiteColor];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容