ios 如何将不透明的 UIView 作为半透明 UIView 的子视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6112220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:04:23  来源:igfitidea点击:

How can I have an opaque UIView as a subview of a semi-transparent UIView?

iphoneiosipad

提问by MusiGenesis

I have a UIView with an alpha of 0.5 which I add as a subview to my primary view in order to gray-out everything else. I want to add an additional UIView to this gray UIView as a subview - the problem is that when I do this, my newly-added subview is also partially transparent.

我有一个 alpha 为 0.5 的 UIView,我将它作为子视图添加到我的主视图中,以便将其他所有内容灰显。我想向这个灰色 UIView 添加一个额外的 UIView 作为子视图 - 问题是当我这样做时,我新添加的子视图也是部分透明的。

Is there any way to make a subview "ignore" the alpha value of its superview and be itself fully opaque?

有没有办法让子视图“忽略”其父视图的 alpha 值并使其本身完全不透明?

采纳答案by Joshua Weinberg

No, not really. What you want is to take your overlay view, and make it just have a clear background color. As a subview of that new overlay place your view that will grey things out. And as a sibling view to that put your view you want to be opaque.

不,不是真的。您想要的是获取叠加视图,并使其具有清晰的背景颜色。作为该新叠加层的子视图,放置您的视图,该视图将使事物变灰。作为一个兄弟视图,你希望你的视图不透明。

[OpaqueView] [DimmingView]
     |             |
      [OverlayView]

回答by Darkngs

Set the UIView background color alpha not it's alpha directly.

设置 UIView 背景颜色 alpha 而不是直接设置 alpha。

Objective-C

目标-C

UIView *view;
...
view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.6];

It's not the same as:

它不同于:

view.backgroundColor = [UIColor blackColor];    
view.alpha = .6;

Swift

迅速

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

回答by Rob Napier

Don't put it inside the semi-transparent view. Make it a sibling to semi-transparent view and put it over it using z-ordering.

不要把它放在半透明视图中。使其成为半透明视图的兄弟,并使用 z 排序将其放在上面。

回答by Hisenberg

This will only work if you have any image on the background.

这仅在背景上有任何图像时才有效。

Instead of reducing the alphaof UIView, add an UIImageViewon that view and then reduce the alpha of the UIImageView.

不是减少alphaof UIView,而是UIImageView在该视图上添加一个,然后减少 的 alpha UIImageView

now add your subviews on the UIView.

现在将您的子视图添加到UIView.

your subviews will not take the alpha property anymore.. :)

您的子视图将不再采用 alpha 属性.. :)

回答by Simon Lee

No, any view will inherit the opacity of its parent.

不,任何视图都将继承其父视图的不透明度。