Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting alpha on UIView sets the alpha on its subviews which should not happen

According to the documentation for UIVIew @property(nonatomic) CGFloat alpha

The value of this property is a floating-point number in the range 0.0 to 1.0, where 0.0 represents totally transparent and 1.0 represents totally opaque. This value affects only the current view and does not affect any of its embedded subviews.

I have a container view configured as follows:

self.myView.backgroundColor = [UIColor blackColor]; self.myView.alpha = 0.5; [self addSubview:self.myView]; 

And then add subviews to 'myView'

[myView addSubView anotherView]; anotherView.alpha = 1; NSLog(@"anotherView alpha = %f",anotherView.alpha); // prints 1.0000 as expected 

But 'anotherView' does have alpha on screen (it is not opaque as expected)

How can this be and what can be done?

like image 505
Avner Barr Avatar asked Sep 08 '13 08:09

Avner Barr


People also ask

What is alpha value in Swift?

Basic Swift Code for iOS Apps View's Alpha value is a floating-point number in the range 0.0 to 1.0, where 0.0 represents totally transparent and 1.0 represents totally opaque. Changing the value of this property updates the alpha value of the current view only.

How do I change the opacity of an image in Swift?

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

What is opaque view in Swift?

An opaque view is expected to fill its bounds with entirely opaque content—that is, the content should have an alpha value of 1. 0 . If the view is opaque and either does not fill its bounds or contains wholly or partially transparent content, the results are unpredictable.


1 Answers

I think this is a bug in the documentation. You should file it at bugreport.apple.com.

Everything I can see after a bit of quick research suggests what you are seeing is how it always has behaved, and my own testing shows it too.

The alpha of a view is applied to all subviews.

Perhaps all you need is [[UIColor blackColor] colorWithAlphaComponent:0.5] but if not you will need to make the view a sibling instead of a child.

like image 112
Abhi Beckert Avatar answered Oct 12 '22 12:10

Abhi Beckert