NSTableView的默認選中行顏色是藍色的背景色,這就不可避免得涉及到自定義NSTableView選中行背景的需求。接下來我就介紹一下兩種解決方法,以及需要注意的地方。
方法一:繼承NSTableRowView
1、新建一個NSTableRowView的子類,重寫- (void)drawSelectionInRect:(NSRect)dirtyRect的方法:
//直接改變點擊背景色的方法
- (void)drawSelectionInRect:(NSRect)dirtyRect
{
if (self.selectionHighlightStyle != NSTableViewSelectionHighlightStyleNone) {
NSRect selectionRect = NSInsetRect(self.bounds, 1, 1);
[[NSColor colorWithWhite:0.9 alpha:1] setStroke]; //設置邊框顏色
[[NSColor redColor] setFill]; //設置填充背景顏色
NSBezierPath *path = [NSBezierPath bezierPathWithRect:selectionRect];
[path fill];
[path stroke];
}
}
//點擊cell呈現(xiàn)自定義圖片的方法
- (void)drawSelectionInRect:(NSRect)dirtyRect
{
if (self.selectionHighlightStyle != NSTableViewSelectionHighlightStyleNone)
{
NSImage *image = [NSImage imageNamed:@"選中"];
NSImageRep *imageRep = image.representations[0];
NSRect fromRect = NSMakeRect(0, 0, imageRep.size.width, imageRep.size.height);
[imageRep drawInRect:dirtyRect fromRect:fromRect operation:NSCompositingOperationSourceOver fraction:1.0 respectFlipped:YES hints:nil];
}
}
2、實現(xiàn)協(xié)議NSTableViewDelegate的- (NSTableRowView )tableView:(NSTableView )tableView rowViewForRow:(NSInteger)row代理方法:
//指定自定義的行
- (nullable NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
CustomTableRowView *rowView = [tableView makeViewWithIdentifier:@"rowView" owner:self];
if (!rowView) {
rowView = [[CustomTableRowView alloc] init];
rowView.identifier = @"rowView";
}
return rowView;
}
3、注意事項:
①、最好不要在控制器中設置tableView的selectionHighlightStyle。如果設置為NSTableViewSelectionHighlightStyleNone,不會有點擊效果;如果設置為NSTableViewSelectionHighlightStyleRegular,可以正常顯示自定義的背景;如果設置為NSTableViewSelectionHighlightStyleSourceList,drawSelectionInRect的方法將不會執(zhí)行。所以還是建議既然你想自定義背景,就不要在在控制器中設置tableView的selectionHighlightStyle了。
②、不要在自定義NSTableCellView的子類中設置self.layer.backgroundColor,這個屬性也將導致自定義的背景不生效。
方法二:繼承NSTableCellView
1、新建一個NSTableCellView的子類,重寫- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle方法:
-(void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle
{
[super setBackgroundStyle:backgroundStyle];
if(backgroundStyle == NSBackgroundStyleDark)
{
self.layer.backgroundColor = [NSColor yellowColor].CGColor;
}
else
{
self.layer.backgroundColor = [NSColor whiteColor].CGColor;
}
}
2、注意事項:
①、這個方法不能設置自定義的圖片
②、這個方法不能設置邊框的顏色