Cocoa osx NSTableview改变行高亮颜色

use*_*901 6 macos cocoa colors highlight nstableview

在我的应用程序中,我有一个基于NSTableView的视图,其中包含一列.行的突出显示颜色设置为常规(蓝色).我需要将该颜色更改为我的自定义颜色.在界面构建器中,我尝试更改它,但唯一的选项是"无,常规和源列表".

我试过这个解决方案但没有成功:https: //stackoverflow.com/a/9594543/3065901

我读到我必须使用这个委托方法,但我不知道如何使用它.

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
Run Code Online (Sandbox Code Playgroud)

我尝试在该方法中绘制行,但是我得到了无效的上下文警告,并且该行仍然保持相同的higlight.请发布一个如何使用此委托方法的简单示例:

需要帮助.提前致谢.

use*_*901 8

从这个链接.

MyNSTableRowView.h

#import <Cocoa/Cocoa.h>
@interface MyNSTableRowView : NSTableRowView
@end
Run Code Online (Sandbox Code Playgroud)

MyNSTableRowView.m

#import "MyNSTableRowView.h"

@implementation MyNSTableRowView
- (id)init
{
    if (!(self = [super init])) return nil;
    return self;
}

- (void)drawSelectionInRect:(NSRect)dirtyRect {
     if (self.selectionHighlightStyle !=    NSTableViewSelectionHighlightStyleNone) {
     NSRect selectionRect = NSInsetRect(self.bounds, 2.5, 2.5);
     [[NSColor colorWithCalibratedWhite:.65 alpha:1.0] setStroke];
     [[NSColor colorWithCalibratedWhite:.82 alpha:1.0] setFill];
     NSBezierPath *selectionPath = [NSBezierPath bezierPathWithRoundedRect:selectionRect
                                                               xRadius:6 yRadius:6];
     [selectionPath fill];
     [selectionPath stroke];
     }
}
@end
Run Code Online (Sandbox Code Playgroud)

AppDelegate.m

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{         
     MyNSTableRowView *rowView = [[MyNSTableRowView alloc]init];
     return rowView;
}
Run Code Online (Sandbox Code Playgroud)


Fel*_*lix 7

这是用户3065901在Swift 3中的答案:

class MyNSTableRowView: NSTableRowView {

    override func drawSelection(in dirtyRect: NSRect) {
        if self.selectionHighlightStyle != .none {
            let selectionRect = NSInsetRect(self.bounds, 2.5, 2.5)
            NSColor(calibratedWhite: 0.65, alpha: 1).setStroke()
            NSColor(calibratedWhite: 0.82, alpha: 1).setFill()
            let selectionPath = NSBezierPath.init(roundedRect: selectionRect, xRadius: 6, yRadius: 6)
            selectionPath.fill()
            selectionPath.stroke()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

NSTableViewDelegate:

func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
    return MyNSTableRowView()
}
Run Code Online (Sandbox Code Playgroud)