Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIControl with transparent background

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?

like image 228
Hesham Avatar asked Feb 18 '23 22:02

Hesham


2 Answers

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.

like image 156
niko34 Avatar answered Feb 28 '23 00:02

niko34


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

like image 37
Harald Scheirich Avatar answered Feb 28 '23 01:02

Harald Scheirich