且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为NSTableView单元格绘制带有边框和背景的文本

更新时间:2023-11-15 13:09:46

如果要坚持使用基于单元格的表视图,则可以将NSCell子类化并覆盖:

If you want to stick with a cell-based table view, you can subclass NSCell and override:

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
    NSRect insetRect = NSInsetRect(cellFrame, 2.0, 2.0);
    NSBezierPath* path = [NSBezierPath bezierPathWithRoundedRect:insetRect xRadius:3.0 yRadius:3.0];
    [path stroke];
    [[NSColor whiteColor] setFill];
    [path fill];
    [[NSColor brownColor] setStroke];
    [path stroke];
    NSMutableAttributedString* content = [[NSMutableAttributedString alloc] initWithString:@"DUPLICATE"];
    NSFontManager* fontManager = [NSFontManager sharedFontManager];
    NSFont* font = [fontManager fontWithFamily:@"Verdana"
                                              traits:NSBoldFontMask
                                              weight:0
                                                size:13.0];
    NSDictionary* attributes = @{NSFontAttributeName:font,
                                 NSForegroundColorAttributeName:[NSColor brownColor]};
    [content setAttributes:attributes range:NSMakeRange(0, [content length])];
    [content setAlignment:NSCenterTextAlignment range:NSMakeRange(0, [content length])];
    [content drawInRect:cellFrame];
}

上面的代码生成了一个与您的按钮相似的单元格(您必须自己调整字体,颜色,线条样式等):

The above code generates a cell that vaguely resembles your button (you'll have to tweak fonts, colours, line-styles etc. yourself):

我还通过提供以下内容来调整了表格视图委托中的行高:

I also adjusted the row height in the table view delegate by providing:

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 24.0;
}