美文网首页
NSTableView选中状态背景色修改

NSTableView选中状态背景色修改

作者: 仗键天涯 | 来源:发表于2019-04-28 16:14 被阅读0次

    NSTableView默认 NSTableViewSelectionHighlightStyle

    NSTableview有三种选中模式

    typedefNS_ENUM(NSInteger,NSTableViewSelectionHighlightStyle) {NSTableViewSelectionHighlightStyleNoneNS_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) {NSRectselectionRect =NSInsetRect(self.bounds,0,0);        [[NSColoryellowColor] setFill];NSBezierPath*selectionPath = [NSBezierPathbezierPathWithRoundedRect:selectionRect xRadius:0yRadius:0];        [selectionPath fill];    }}

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

    - (NSTableRowView*)tableView:(NSTableView*)tableView rowViewForRow:(NSInteger)row{    YLTableRowView *rowView = [[YLTableRowView alloc] init];returnrowView;}

    继承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{    [supersetBackgroundStyle:backgroundStyle];if(backgroundStyle ==NSBackgroundStyleDark)    {self.backgroundColor = [NSColoryellowColor];    }else{self.backgroundColor = [NSColorwhiteColor];    }}

    上边都是基于View-Base的TableView,在10.6以前的代码还是用到cell-base,这种情况下要修改选中状态行的背景色,可以重载NSTableview函数:

    - (void)highlightSelectionInClipRect:(NSRect)clipRect

    {

        if (_customHighlightColor) {

            [_customHighlightColor set];

            NSRectFillUsingOperation([self rectOfRow:self.selectedRow],NSCompositeSourceOver);

        }

        else{

            [super highlightSelectionInClipRect:clipRect];

        }

    }

    另外,也可能需要重载NSCell函数:

    - (NSColor*) highlightColorWithFrame:(NSRect)inFrame inView:(NSView*)inView

    {

        NSColor* color = [super highlightColorWithFrame:inFrame inView:inView];

        if([inViewrespondsToSelector:@selector(customHighlightColor)])

        {

            color = [(IMBTableView*)inView customHighlightColor];

        }

        returncolor;

    }

    相关文章

      网友评论

          本文标题:NSTableView选中状态背景色修改

          本文链接:https://www.haomeiwen.com/subject/udqjnqtx.html