macOS开发Tips

NSTableView 选中行背景色

2016-12-06  本文已影响1266人  TessmileLu

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])两种。
在开发过程中,根据需求会有改变选中状态下行背景色的情况。下面为将介绍两种改变背景色的方法。

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

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];
    }
}
上一篇 下一篇

猜你喜欢

热点阅读