2

我遇到了一个关于使用自定义 NSTableHeaderCell 清除 NSTableView 背景的问题。当我调整表格列的大小时。

在此处输入图像描述

// The method for setting NSTableView in some place
// NSScrollView disabled Draw Background
- (void)setMainTableView:(NSTableView *)mainTableView {

     _mainTableView = mainTableView;
     [_mainTableView setBackgroundColor:[NSColor clearColor]];

     [[_mainTableView tableColumns] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        NSString *columnTitle = [[obj headerCell] stringValue];
        MyTableHeaderCell *myCell = [[MyTableHeaderCell alloc] initTextCell:columnTitle];
        [obj setHeaderCell:myCell];
    }];
 }

//  Overriding NSTableHeaderCell Method
- (void)drawWithFrame:(CGRect)cellFrame inView:(NSView *)view {

    [[NSColor redColor] set];
    NSFrameRect(cellFrame);

    [super drawInteriorWithFrame:cellFrame inView:view];
}
4

3 回答 3

3

+1 拉杜

具体来说,对于任何关心.. 在 Swift 中执行此类操作的人,您可以执行以下操作:

final class MyTableHeaderCell : NSTableHeaderCell
{
    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }

    override init(textCell: String)
    {
        super.init(textCell: textCell)
        // you can also set self.font = NSFont(...) here, too!        
    }

    override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView)
    {
        super.drawWithFrame(cellFrame, inView: controlView) // since that is what draws borders
        NSColor().symplyBackgroundGrayColor().setFill()
        NSRectFill(cellFrame)
        self.drawInteriorWithFrame(cellFrame, inView: controlView)
    }

    override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView)
    {
        let titleRect = self.titleRectForBounds(cellFrame)
        self.attributedStringValue.drawInRect(titleRect)
    }
}
于 2016-09-29T02:30:04.600 回答
1

任何先前的像素都应在任何绘图之前由 api 自动清除。您似乎发现了一个仅在调整大小时发生的故障。一种解决方法是自己清除像素。只需在绘制其他任何内容之前用白色(或您的背景颜色)填充 cellFrame 矩形。

于 2014-05-07T14:22:41.350 回答
0

Michaels 解决方案的 Swift 5 解决方案:

final class MyTableHeaderCell : NSTableHeaderCell
{
    override init(textCell: String)
    {
        super.init(textCell: textCell)
        // you can also set self.font = NSFont(...) here, too!
    }
    
    required init(coder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView)
    {
        super.draw(withFrame: cellFrame, in: controlView) // since that is what draws borders
        NSColor.gray.setFill()
        cellFrame.fill()
        self.drawInterior(withFrame: cellFrame, in: controlView)
    }

    override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView)
    {
        let titleRect = self.titleRect(forBounds: cellFrame)
        self.attributedStringValue.draw(in: titleRect)
    }
}
于 2020-09-04T15:55:30.970 回答