NSBrowser图像没有在单元格中显示



我使用NSBrowser视图来显示finder类型应用程序中的文件和文件夹列表。

问题是,当我尝试在willDisplayCell方法中设置图像时。视野中没有显示任何东西。

代码:

// This is a utility method to find the parent item for a given column. The item based API eliminates the need for this method.
- (FileSystemNode *)parentNodeForColumn:(NSInteger)column {
    if (_rootNode == nil) {
        _rootNode = [[FileSystemNode alloc] initWithURL:[NSURL fileURLWithPath:@"/Users/kiritvaghela"]];
    }
    FileSystemNode *result = _rootNode;
    // Walk up to this column, finding the selected row in the column before it and using that in the children array
    for (NSInteger i = 0; i < column; i++) {
        NSInteger selectedRowInColumn = [_browser selectedRowInColumn:i];
        FileSystemNode *selectedChildNode = [result.children objectAtIndex:selectedRowInColumn];
        result = selectedChildNode;
    }
    return result;
}
- (void)browser:(NSBrowser *)browser willDisplayCell:(NSBrowserCell *)cell atRow:(NSInteger)row column:(NSInteger)column {
    FileSystemNode *parentNode = [self parentNodeForColumn:column];
    FileSystemNode *childNode = [parentNode.children objectAtIndex:row];
    [cell setTitle:childNode.displayName];
    cell.image = node.icon;
}

Apple simplecocoabbrowser示例

而cellPrototype的默认值是NSBrowserCell,它似乎使用了NSTextFieldCell。(macOS 10.14)

要解决这个问题,您需要子类NSBrowserCell并将子类设置为cellClass: [_browser setCellClass:[BrowserCell class]];

@interface BrowserCell : NSBrowserCell
@end
@implementation BrowserCell
@end

另一个问题是叶指示符。它将显示两次,一次来自单元格,一次来自浏览器。

- (void)browser:(NSBrowser *)browser willDisplayCell:(NSBrowserCell *)cell atRow:(NSInteger)row column:(NSInteger)column {
    FileSystemNode *parentNode = [self parentNodeForColumn:column];
    FileSystemNode *childNode = [parentNode.children objectAtIndex:row];
    NSImage *image = node.icon;
    [image setSize:NSMakeSize(16, 16)];
    cell.image = cell.image;
    cell.leaf = YES;
}

雷达://47175910

使用catlan的回答中描述的NSBrowserCell工作,但是NSTextField在绘制选定单元格的背景时的行为与NSBrowserCell不同。当鼠标在另一列中点击/拖动时,NSBrowserCell会将选中单元格的蓝色背景绘制为灰色(Finder也会这样做)。然而,当鼠标被点击时,NSTextFieldCell仍然保持蓝色,并在释放时变为灰色。因为叶子指示器不是由NSBrowserCell绘制的,单元格的那个区域仍然会有一个蓝色的选择高亮,所以单元格同时有蓝色和灰色作为背景色。这是简短的,因为它只是在点击的时候,但它看起来是错误的。

让NSBrowserCell表现得像NSTextFieldCell需要一些逆向工程和私有api,所以我决定做正确的事情就是子类NSTextFieldCell并在其中绘制一个图标。代码是这样的,

@implementation BrowserTextFieldCell
- (void)drawInteriorWithFrame:(NSRect)cellFrame controlView:(NSView *)controlView
{
    __auto_type textFrame = cellFrame;
    __auto_type inset = kIconHorizontalPadding * 2 + kIconSize;
    textFrame.origin.x += inset;
    textFrame.size.width -= inset;
    [super drawInteriorWithFrame:textFrame inView:controlView];
    [self drawIconWithFrame:cellFrame];
}
- (void)drawIconWithWithFrame:(NSRect)cellFrame
{
    NSRect iconFrame = cellFrame;
    iconFrame.origin.x += kIconPadding;
    iconFrame.size = NSMakeSize(kIconSize, kIconSize);
    [self.iconImage drawInRect:iconFrame];
}
@end

相关内容

最新更新