UIControl具有透明背景

Hes*_*gid 4 iphone uicontrol ios

我有一个UIControl子类.我使用以下代码更改它的背景颜色:

- (void)drawRect:(CGRect)rect
{
    [self.backgroundColor setFill];
    UIRectFill([self bounds]);
}
Run Code Online (Sandbox Code Playgroud)

这适用于所有颜色,除了[UIColor clearColor].如何制作UIControl透明背景?

nik*_*o34 5

您应该在initWithFrame或/和initWithCoder中设置清晰的背景颜色

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

控件的默认背景将是透明的,然后您可以根据需要填充drawRect中的任何背景颜色.

它在您的示例中不起作用的原因是控件具有默认的黑色背景,该背景设置在drawRect的某个位置(可能在父UIView init中).设置彩色背景时,它会覆盖黑色背景.设置清除后,您会看到默认的黑色背景.