21

I want to add a UIView to my UIViewController but I want it to be transparent until I decide to create an Oval inside the UIView.

Until I create the oval, I can set my view's alpha to 0 but when I want to add the oval, the background color is still black.

here's what it looks like with a bunch of ovals

image

In my UIView:

- (void)drawRect:(CGRect)rect
{
    [self pushContext];
    UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
    [[UIColor redColor] setFill];
    [oval fill];
    self.opaque = NO;
    [self setBackgroundColor:[UIColor clearColor]];

    [oval addClip];
    [self setBackgroundColor:[UIColor clearColor]];

    [self popContext];
}
diablo1234
  • 379
  • 2
  • 3
  • 10

5 Answers5

29

Please try to use this one

view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
view.opaque = NO;
Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
18
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        self.opaque = NO;

    }
    return self;
}



- (void)drawRect:(CGRect)rect
{
    [[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.0] setFill];
    UIRectFill(rect);
    [self pushContext];
    UIBezierPath *oval = [UIBezierPath bezierPathWithOvalInRect:self.bounds];
    [[UIColor redColor] setFill];
    [oval fill];

    [oval addClip];

    [self popContext];
}
Guo Luchuan
  • 4,729
  • 25
  • 33
5

In your ViewController, you could say that opaque is NO. Let's say, your view is named myCustomView.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myCustomView.opaque = NO;   
}

Or you could just go to the storyboard and uncheck the opaque checkbox like- enter image description here

Natasha
  • 6,651
  • 3
  • 36
  • 58
4

I did semi-transparent background for my UIViewController the same way as it's recommended here but it didn't work until I set modalPresentationStyle to .custom

my Swift 4 code:

modalPresentationStyle = .custom
view.isOpaque = false
view.backgroundColor = UIColor.black.withAlphaComponent(0.2)

I open my controller from another one using present(controller, anim, completion) method.

Northern Captain
  • 1,147
  • 3
  • 25
  • 32
  • Thanks for the tip. I was scratching my head on this for quite a while until I saw your answer. I changed `modalPresentationStyle` to `.custom` and it worked for me too! – Brian Sachetta Apr 09 '20 at 21:29
3

In Swift 3.x: (where layer is the view)

layer.backgroundColor = UIColor.clear.cgColor
layer.isOpaque = false
Matt
  • 693
  • 9
  • 16