cocoa - 自定义 NSTextFieldCell 和背景绘制

标签 cocoa nstextfield nstextfieldcell

我创建了一个自定义 NSTextFieldCell 并覆盖了 - (void)drawInteriorWithFrame: (NSRect)cellFrame inView: (NSView *)controlView 来在这里进行我自己的绘图。但是,我在背景绘制方面遇到了麻烦。如果不调用 super ,背景就不会被清除,后续的绘图会产生类似涂抹效果的效果。当设置drawsBackground时,这种情况不会发生,因为在这种情况下我可以用背景颜色填充cellFrame。

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

    [self.attributedStringValue drawInRect: cellFrame];
}

enter image description here

但是,如果背景绘制被禁用,我该怎么做才能清除背景呢?我当然想让 TextView 下的其他内容闪耀(所以,仅仅用 super View 的背景颜色删除是不行的)。

最佳答案

如果您尝试使用[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];
    }
}

关于cocoa - 自定义 NSTextFieldCell 和背景绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24468891/

相关文章:

Objective-C/C 将 UTF8 文字转换为真正的字符串

objective-c - 一个托管对象上下文的两个持久存储 - 可能吗?

cocoa - NSTextFieldCell 的 cellSizeForBounds : doesn't match wrapping behavior?

cocoa - 对齐 NSTextField 和图像

objective-c - NSScrollView 滚动条绘制在所有 View 之上

macos - NSDatePicker 操作方法未触发

cocoa - NSNumberFormatter 因 nil 值而失败

objective-c - 在结束编辑时执行操作

swift - 在 Swift 中使用 Tab 键选择下一个 NSTextField

swift - 在 MacOS 应用程序的 NSTextFieldCell (Swift 3) 中自动调整文本大小