I have a UIControl
subclass. I use the following code the change it's background color:
- (void)drawRect:(CGRect)rect
{
[self.backgroundColor setFill];
UIRectFill([self bounds]);
}
This works fine for all colors except [UIColor clearColor]
. How can I make the background of the UIControl
transparent?
You should set the a clear background color in the initWithFrame or/and 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;
}
the default background of your control will be transparent, and you will then be able to fill any background color in the drawRect if you want.
The reason it doesn't work in your example is that the control have a default black background that is set somewhere ouside the drawRect (probably in the parent UIView init). When you set a colored background, it comes over the black one. When you set a clear one, you see the default black background.
For a UIControl
which is a subclass of UIView
self.backgroundColor = [UIColor <anycolor>];
should be sufficient, as @niko34 described, if you want the control to have a transparent color i.e. [UIColor clearColor]
or any other color that has any kind of transparency you also need to set
self.opaque = NO;
otherwise any transparent color will be drawn in a nontransparent manner
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With