web-dev-qa-db-fra.com

Rendre UIView transparent

Je souhaite ajouter un UIView à mon UIViewController, mais je souhaite qu'il soit transparent jusqu'à ce que je décide de créer un ovale dans UIView.

Jusqu'à ce que je crée l'ovale, je peux définir l'alpha de ma vue sur 0, mais lorsque je veux ajouter l'ovale, la couleur d'arrière-plan est toujours noire.

voici à quoi il ressemble avec un tas d'ovales

image

Dans mon 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];
}
11
peter1234
- (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];
}
15
Guo Luchuan

S'il vous plaît essayez d'utiliser celui-ci

view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];
view.opaque = NO;
25
Dharmbir Singh

Dans votre ViewController, vous pouvez dire que l'opaque est NON. Disons que votre vue s'appelle myCustomView.

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

Ou vous pouvez simplement aller dans le storyboard et décocher la case opaque comme -  enter image description here

5
Natasha

Dans Swift 3.x: (/ layer est la vue )

layer.backgroundColor = UIColor.clear.cgColor
layer.isOpaque = false
1
Matt

J'ai fait un fond semi-transparent pour mon UIViewController de la même manière que c'est recommandé ici, mais cela n'a pas fonctionné jusqu'à ce que je règle modalPresentationStyle à .custom

mon Swift 4 code:

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

J'ouvre mon contrôleur à partir d'un autre en utilisant la méthode actuelle (contrôleur, animation, achèvement).

0
Northern Captain