4

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

- (void)drawRect:(CGRect)rect
{
    [self.backgroundColor setFill];
    UIRectFill([self bounds]);
}

这适用于所有颜色,除了[UIColor clearColor]. 我怎样才能使UIControl透明的背景?

4

3 回答 3

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

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

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

于 2013-01-11T15:54:32.600 回答
3

对于 aUIControl的子类UIView

self.backgroundColor = [UIColor <anycolor>]; 

应该足够了,正如@niko34 所描述的,如果您希望控件具有透明颜色,即[UIColor clearColor]或任何其他具有任何透明度的颜色,您还需要设置

self.opaque = NO;

否则任何透明颜色都将以不透明的方式绘制

于 2013-01-11T16:17:56.050 回答
0

Try setting alpha to 0.5 or below and I think it should show a semi transparent background with a black tint like [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5]

于 2014-09-11T12:35:55.247 回答