自定义NSTableHeaderCell,用于清晰的NSTableView背景

时间:2013-10-17 08:07:20

标签: cocoa

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

enter image description here

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

+1到Radu

具体而言,对于任何关心...在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)
    }
}

答案 2 :(得分: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)
    }
}