100% opacity UILabel over a 50% opacity background (UIView?)

Objective CIphoneUser InterfaceUilabel

Objective C Problem Overview


So right now I have a UIView with a UILabel in it. I want the background to have an opacity < 1.0 and the label to have an opacity of 1.0. However since alphas propagate down the view hierarchy, the label ends up with an opacity < 1.0 as well.

Is there anyway to do what I want without making the UILabel a subview of another view??

Objective C Solutions


Solution 1 - Objective C

Just set the background color to be semitransparent:

view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];

Or, in Swift:

view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)

Or, Swift 3:

view.backgroundColor = UIColor.black.withAlphaComponent(0.5)

Note that, in this particular case, UIColor(white: 0, alpha: 0.5) is more concise, but colorWithAlphaComponent will work in general.

Solution 2 - Objective C

Besides being available in code, you can do this quite easily from iB as well:

  1. Within the storyboard, select the view you wish to edit;
  2. From the right panel, make sure the Attributes inspector is opened;
  3. Click on the right side of the "Background" drop down box and choose "Other ..."; it will open a colour picker dialog;
  4. Change the "Opacity" at the bottom to set the background colour opacity.

Solution 3 - Objective C

You can set the background color of the UIView with a semi-transparent color or make the image itself semi-transparent. This way it's a property of the view that is transparent, not the view itself.

Solution 4 - Objective C

You can use this:

self.view.layer.opacity=0.5

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDevDevDevView Question on Stackoverflow
Solution 1 - Objective CIan HenryView Answer on Stackoverflow
Solution 2 - Objective CJa͢ckView Answer on Stackoverflow
Solution 3 - Objective CColin GislasonView Answer on Stackoverflow
Solution 4 - Objective Camedc111View Answer on Stackoverflow