Draw Text with a border and background for a NSTableView cell

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 06:56:05

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/23236703/draw-text-with-a-border-and-background-for-a-nstableview-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!