UIControl with transparent background

I have a subclass of UIControl . I am using the following code: change the background color:

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

This works great for all colors except [UIColor clearColor] . How to make UIControl background transparent?

+4
source share
3 answers

You must set the background color to pure in 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 background of your control will be transparent by default, and then you can fill in any background color in drawRect if you want.

The reason this doesn't work in your example is because the control has a default black background that is set somewhere next to drawRect (possibly in the parent UIView init). When you set the color background, it comes in black. When you set clear, you will see a black background by default.

+5
source

With a UIControl , which is a subclass of UIView

 self.backgroundColor = [UIColor <anycolor>]; 

should be enough as described in @ niko34 if you want the control to have a transparent color, i.e. [UIColor clearColor] or any other color that has any transparency, you also need to set

 self.opaque = NO; 

otherwise, any transparent color will be drawn in an opaque manner

+3
source

Try setting alpha 0.5 or lower, and I think it should show a translucent background with a black tint, for example [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5]

0
source

All Articles