在UIView上设置alpha会在其子视图上设置不应发生的alpha

问题描述 投票:78回答:9

根据UIVIew @property(nonatomic) CGFloat alpha的文档

此属性的值是0.0到1.0范围内的浮点数,其中0.0表示完全透明,1.0表示完全不透明。此值仅影响当前视图,不会影响其任何嵌入的子视图。

我有一个容器视图配置如下:

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

然后将子视图添加到'myView'

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

但'anotherView'在屏幕上确实有alpha(它不像预期的那样不透明)

这怎么可能,可以做些什么?

ios objective-c uiview alpha-transparency
9个回答
110
投票

我认为这是文档中的错误。你应该在bugreport.apple.com上提交。

经过一些快速研究后我能看到的一切表明你所看到的是它总是表现得如何,我自己的测试也表明了这一点。

视图的alpha应用于所有子视图。

也许你需要的只是[[UIColor blackColor] colorWithAlphaComponent:0.5],但如果不是你需要让视图成为兄弟而不是孩子。


0
投票

请参阅Xcode文档中的粗体描述。

此属性的值是0.0到1.0范围内的浮点数,其中0.0表示完全透明,1.0表示完全不透明。更改此属性的值仅更新当前视图的Alpha值。但是,该alpha值赋予的透明度会影响所有视图的内容,包括其子视图。例如,嵌入在alpha值为0.5的父视图中的alpha值为1.0的子视图出现在屏幕上,就好像它的alpha值也是0.5一样。


41
投票

不要直接在父视图上设置alpha。而不是使用下面的代码行,它将透明度应用于父视图而不影响其子视图。

[parentView setBackgroundColor:[[UIColor clearColor] colorWithAlphaComponent:0.5]];


25
投票

在迅速

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

更新SWIFT 3

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

17
投票

设置背景颜色的不透明度而不是alpha不会影响其子视图。

  1. 选择视图。
  2. 转到属性检查器而不是背景颜色
  3. 点击“其他”
  4. 将不透明度设置为30%

或者您可以通过编程方式进行设置

var customView:UIView = UIView()
customView.layer.opacity = 0.3

而已。快乐的编码!!!


15
投票

如果您喜欢Storyboards,请在User Defined Runtime Attribute中为您的视图添加Identity Inspector

Key Path: backgroundColorType: ColorValue:,例如白色,不透明度50%。


6
投票

所讨论的最简单的解决方案是更改alpha,如下所示:Xcode 8 Swift 3的更新版本是:

yourParentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)

目标C:

yourParentView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];

请参阅Apple Developer Docs:https://developer.apple.com/reference/uikit/uiview/1622417-alpha


2
投票

这是一个有点复杂的解决方案:

UIView *container;
UIView *myView;
UIView *anotherView;

myView.alpha = 0.5;
[container addSubview:myView];

anotherView.alpha = 1;
[container addSubview:anotherView];

使用container视图作为superview,anotherViewmyView都是container的子视图,anotherView不是myView的子视图。


2
投票

在Swift 4.2和Xcode 10.1中

不要通过故事板添加颜色和alpha值。在这种情况下,只有程序化方法才有效。

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

1
投票

目前,只有一种方法可以使父视图透明,并且不将任何子视图放入(不要将任何视图作为子视图)父视图,将子视图放在父视图之外。要使父视图透明,您可以通过故事板进行此操作。

//Transparent the parentView

parentView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)

将另一个视图放在父视图之外。它会像魅力一样工作。

© www.soinside.com 2019 - 2024. All rights reserved.