简体   繁体   English

在NSSearchField子类的drawRect中设置背景色

[英]Setting background color in drawRect of NSSearchField subclass

I have a custom subclass of NSSearchField that I would like to set the background color of. 我有一个NSSearchField的自定义子类,我想设置其背景色。

@interface CustomNSSearchField : NSSearchField
@end

So far, I have tried: 到目前为止,我已经尝试过:

Attempt #1 尝试#1

@implementation CustomNSSearchField

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];

    [self setDrawsBackground:YES];
    [self setBackgroundColor:[NSColor redColor]];
}

which resulted in no visual changes at all: 完全没有视觉变化:

尝试1

I then followed the suggestions here and also tried: 然后,我按照这里的建议进行尝试:

Attempt #2 尝试#2

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];

    [[NSColor redColor] setFill];
    NSRectFill(rect);
}

Which results in this: 结果是:

尝试2

How do I set the background color inside the bounds and behind the text of the search field? 如何设置的范围 ,搜索领域的文本后面的背景颜色?

You have to redraw the entire thing. 您必须重新绘制整个内容。 There is no property, to specifically change the background-color of the NSSearchField. 没有属性来专门更改NSSearchField的背景颜色。 Check out this example: 看看这个例子:

Custom NSSearchField 自定义NSSearchField

Edit: 编辑:

Also what's worth to point out. 还有值得指出的地方。 You should never override the controls drawRect method. 您永远不应覆盖控件的drawRect方法。 You should rather make a subclass of NSSearchFieldCell . 您应该创建NSSearchFieldCell的子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM