Why do all the subviews of a UIView show translucency when the UIView's alpha is set less than 1.0?

StackOverflow https://stackoverflow.com/questions/23676184

Frage

On clicking a UIButton, i create a UIView and bring it front. I set its "alpha=0.6" to show translucency and then i add various "subviews" to it. Somehow, these "subviews" too show translucency which i don't want. Thanks!

- (IBAction)OnClickTutorialGuideButton:(id)sender
{
    dimView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    dimView.backgroundColor = [UIColor blackColor];
    dimView.alpha = 0.4;
    [self.view addSubview:dimView];
    [self.view bringSubviewToFront:dimView];

    [UIView animateWithDuration:0.3
                     animations:^{
                         dimView.alpha = 0.6;
                     }];

    // Label
    UILabel *getStartedLabel=[[UILabel alloc]initWithFrame:CGRectMake(72, 50, 176, 25)];
    getStartedLabel.text=@"Getting Started";
    getStartedLabel.textColor=[UIColor colorWithRed:(243.0/255.0) green:(107.0/255.0) blue:(55.0/255.0) alpha:1.0];
    getStartedLabel.font=[UIFont boldSystemFontOfSize:25.0f];
    [dimView addSubview:getStartedLabel];

    // ImageView
    UIImageView *remImage=[[UIImageView alloc]initWithFrame:CGRectMake(68, 90, 180, 180)];
    remImage.image=[UIImage imageNamed:@"getting_started1_large_icon.png"];
    [dimView addSubview:remImage];
}

a) before:

enter image description here

b) after:

enter image description here

War es hilfreich?

Lösung

Here comes from Apple's View and Window Architecture documentation:

In addition to providing its own content, a view can act as a container for other views. When one view contains another, a parent-child relationship is created between the two views. The child view in the relationship is known as the subview and the parent view is known as the superview. The creation of this type of relationship has implications for both the visual appearance of your application and the application’s behavior.

So when you set dimView.alpha = 0.4;(which is your super view) it automatically changes the opacity of it's sub views too. Because your super view holds those sub views and underlying layers which drawn by Core Animation.

If you want to change opacity of your super view only, you can do this via:

[dimView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.5]]; 

See also:

Andere Tipps

It happens because you are setting alpha of overall container view of the subviews. You should try to set it background color with desired alpha value to achieve what you are looking for.

A view is in one sense a graphics context first and foremost. Subviews live in that context and their own contexts are relative to the contexts above them in the same view hierarchy. To get something different you need views outside of the view whose alpha is less than 1.0

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top