基于视图的 NSTableView 选择?

View-based NSTableView selection?

我写了一个基于视图的tableview,像这样:

我用NSTableRowView绘制选区,代码是这样的:

- (void)drawRect:(NSRect)dirtyRect {
  [[NSColor clearColor] setFill];
  if (self.isClicked) {
    [[[NSColor blackColor] colorWithAlphaComponent:0.08] setFill];
  }
  NSRect rowViewRect = NSMakeRect(0, 0, 274, 72);
  NSBezierPath *path = [NSBezierPath bezierPathWithRect:rowViewRect];
  [path fill];
}

但最后,我发现TableRowView没有盖住tableView,所以selectedColor没有盖住图片和按钮,更像是背景色,但我需要让selected TableRowView盖住视图,就像这样:

所选颜色覆盖图像和按钮。我用谷歌搜索,但没有找到任何想法。感谢帮助~

所以这有点棘手。该策略是在您的 NSTableCellView 中使用 alpha 小于 1 的叠加彩色视图,然后根据单元格的选择添加和删除它。

首先,你需要一个可以设置背景色的NSView:

NSView_Background.h

@interface NSView_Background : NSView 
@property (nonatomic, strong) NSColor *background;
@end

NSView_Background.m

#import "NSView_Background.h"

@implementation NSView_Background

- (void)drawRect:(NSRect)dirtyRect {
    [self.background set];
    NSRectFill([self bounds]);
}

- (void)setBackground:(NSColor *)color {
    if ([_background isEqual:color]) return;

    _background = color;

    [self setNeedsDisplay:YES];
}
@end

其次,在你的NSTableCellView子类中,添加一个NSView_Background 属性:

#import "NSView_Background.h"

@interface
@property (nonatomic, strong) NSView_Background *selectionView;
@end

第三种,将此方法添加到NSTableCellView子类中:

- (void)shouldShowSelectionView:(BOOL)shouldShowSelectionView {
    if (shouldShowSelectionView) {
        self.selectionView = [[NSView_Background alloc] init];
        [self.selectionView setBackground:[NSColor grayColor]];
        self.selectionView.alpha = 0.4;
        [self addSubview:self.selectionView];

        [self setNeedsDisplay:YES];   // draws the selection view
    } else {
        [self.selectionView removeFromSuperview];
        self.selectionView = nil;
    }
}

第四,在你的 NSTableCellView 子类的 drawRect 中添加这个:

- (void)drawRect:(NSRect)dirtyRect {
    if (self.selectionView)
        self.selectionView.frame = self.bounds;
}

最后,覆盖NSTableCellView:setBackgroundStyle:

- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
    switch (backgroundStyle) {
        case: NSBackgroundStyleDark:
            [self shouldShowSelectionView:YES];
            break;
        default:
            [self shouldShowSelectionView:NO];
            break;
    }
}

我知道这看起来很老套,但这是我获得此行为的唯一方法。希望这对您有所帮助,祝您好运!