为NSTableView单元格绘制带有边框和背景的文本 [英] Draw Text with a border and background for a NSTableView cell

查看:156
本文介绍了为NSTableView单元格绘制带有边框和背景的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于单元格的表视图,并且希望在此表视图中显示某种标签,最好不必使用基于视图的表视图.

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.

是否有一种优雅的方法来实现类似此处的示例(HTML)的效果,理想情况下还具有背景色.

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

推荐答案

如果要坚持使用基于单元格的表视图,则可以将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;
}

这篇关于为NSTableView单元格绘制带有边框和背景的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆