NSTableView 選中行背景色

NSTableView默認(rèn) NSTableViewSelectionHighlightStyle

NSTableview有三種選中模式

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

默認(rèn)模式為NSTableViewSelectionHighlightStyleRegular在此種模式下,行選中顏色有l(wèi)ight blue ([NSColor alternateSelectedControlColor]) 和 light gray color ([NSColor secondarySelectedControlColor])兩種。
在開發(fā)過程中,根據(jù)需求會(huì)有改變選中狀態(tài)下行背景色的情況。下面為將介紹兩種改變背景色的方法。

  • 繼承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];
    }
}

實(shí)現(xiàn)協(xié)議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自動(dòng)設(shè)置,可根據(jù)backgroudStyle的類型對(duì)cellView的背景色進(jìn)行控制。

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];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容