Cocoa 自定义NSTextFieldCell和背景图形

Cocoa 自定义NSTextFieldCell和背景图形,cocoa,nstextfield,nstextfieldcell,Cocoa,Nstextfield,Nstextfieldcell,我创建了一个自定义的NSTextFieldCell,并在这里重写了-(void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView,以进行我自己的绘图。然而,我有麻烦的背景画。如果不调用super,背景不会被清除,后续的图形会产生类似涂抹效果的效果。设置drawsBackground时不会发生这种情况,因为在本例中,我可以用背景色填充单元格框 - (void)drawInteriorWithFrame: (NSR

我创建了一个自定义的NSTextFieldCell,并在这里重写了
-(void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
,以进行我自己的绘图。然而,我有麻烦的背景画。如果不调用
super
,背景不会被清除,后续的图形会产生类似涂抹效果的效果。设置drawsBackground时不会发生这种情况,因为在本例中,我可以用背景色填充单元格框

- (void)drawInteriorWithFrame: (NSRect)cellFrame inView: (NSView *)controlView {
    if (self.drawsBackground) {
        [self.backgroundColor set];
    } else {
        [NSColor.clearColor set];
    }
    NSRectFill(cellFrame);

    [self.attributedStringValue drawInRect: cellFrame];
}


但是如果背景绘图被禁用,我需要做什么来清除背景呢?当然,我想让文本视图下的其他内容显示出来(因此,仅使用superview的背景色进行擦除并不是解决方案)。

如果您尝试使用
[NSColor clearColor]
填充单元格,它会将其绘制为黑色。 当不需要填充时,尽量避免填充。您将能够删除您的
super
呼叫

例如:

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    if (self.drawsBackground) {
        if (self.backgroundColor && self.backgroundColor.alphaComponent>0) {

            [self.backgroundColor set];
            NSRectFill(cellFrame);
        }
    }
    NSRect titleRect = [self titleRectForBounds:cellFrame];
    NSAttributedString *aTitle = [self attributedStringValue];
    if ([aTitle length] > 0) {
        [aTitle drawInRect:titleRect];
    }
}