Draw Text with a border and background for a NSTab

2019-08-07 07:12发布

I have a cell-based tableview and I want to display some sort of tags within this tableview, preferably without having to use a view-based tableview.

Is there an elegant way to achieve something like the example here (HTML), ideally with a background-color as well.

Example

1条回答
趁早两清
2楼-- · 2019-08-07 08:02

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):

enter image description here

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

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 24.0;
}
查看更多
登录 后发表回答