我有一个UIControl
子类。我使用以下代码更改它的背景颜色:
- (void)drawRect:(CGRect)rect
{
[self.backgroundColor setFill];
UIRectFill([self bounds]);
}
这适用于所有颜色,除了[UIColor clearColor]
. 我怎样才能使UIControl
透明的背景?
您应该在 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 中)。当您设置彩色背景时,它会覆盖黑色背景。当您设置一个清晰的,您会看到默认的黑色背景。
对于 aUIControl
的子类UIView
self.backgroundColor = [UIColor <anycolor>];
应该足够了,正如@niko34 所描述的,如果您希望控件具有透明颜色,即[UIColor clearColor]
或任何其他具有任何透明度的颜色,您还需要设置
self.opaque = NO;
否则任何透明颜色都将以不透明的方式绘制
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]