如何在当前视图上创建一个半透明的视图层?

22

你可能以前见过这个,在ScoutMob等消费者应用程序中变得越来越流行。我正在尝试在启动时实现一个60%透明度的视图,它将覆盖我的主屏幕,解释如何使用主屏幕的功能,并在轻触时消失。

我已经完成了整个应用(它使用.xib文件因为它是几年前创建的,但随意解释故事板格式,因为我可能会在其他iOS 5.0+应用程序中重复使用此功能。)

我制作单个视图没有问题,但是临时将一个视图层叠在另一个视图上是我还没有直观理解的。我将继续研究并包含任何有用的提示,以防其他人尝试做同样的事情。


1
一个相关的问题,尽管有点过时。 - user
5个回答

51
// get your window screen size
CGRect screenRect = [[UIScreen mainScreen] bounds];
//create a new view with the same size
UIView* coverView = [[UIView alloc] initWithFrame:screenRect];
// change the background color to black and the opacity to 0.6
coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
// add this new view to your main view
[self.view addSubview:coverView];

完成后,您可以将其删除:

[coverView removeFromSuperview];

Swift3版本:

// get your window screen size
let screenRect = UIScreen.main.bounds
//create a new view with the same size
let coverView = UIView(frame: screenRect)
// change the background color to black and the opacity to 0.6
coverView.backgroundColor = UIColor.black.withAlphaComponent(0.6)        
// add this new view to your main view
self.view.addSubview(coverView)

要删除它:

coverView.removeFromSuperview()

4

您可以使用UITextView和UIButton轻松实现此操作。只需将UITextView放置在屏幕上,并使用要显示的内容使其成为全屏幕大小,然后将背景颜色更改为黑色背景,并设置背景透明度为0.6即可。

[UIColor colorWithRed: 0 withGreen: 0 withBlue: 0 withAlpha: .6];

将按钮作为子视图放在最上面,使其占据整个屏幕的框架,并将其alpha值设置为0。将按钮的动作设置为隐藏文本视图和按钮。
示例:
UITextView* textview = [[UITextView alloc] initWithFrame:self.view.frame];
[textview setText: @"Text here"];
[textview setBackgroundColor: [UIColor colorWithRed: 0 withGreen: 0 withBlue: 0 withAlpha: .6]];
[textview setTextColor: [UIColor whiteColor]];
[self.view addSubview: textview];

UIButton* btn = [[UIButton alloc] initWithFrame:self.view.frame];
[btn setAlpha:0];
[btn addTarget:self action:@selector(method) forEvent:UIControlEventTouchUpInside];
[self.view addSubview: btn];

您可能需要检查addTarget:方法;我不确定这些是否是我脑海中正确的参数。


1
  1. 创建一个UIView,随意命名(dimBackgroundUIView),然后将背景颜色设置为黑色,并将alpha设置为0.1或0.2等。
  2. 在需要变暗背景时添加以下两行代码:[self.view addSubview:dimBackgroundUIView]; [self addConstraintsForDimView];
  3. 当您想要移除变暗背景时,请添加以下两行代码:if(dimBackgroundUIView) [dimBackgroundUIView removeFromSuperview];
  4. 不要忘记为dimBackgroundUIView添加约束(布局)。

请查看:iOS Dim background when a view is shown

不要忘记阅读代码下面的注释以了解您需要做什么。


1

只需创建一个机制,判断是否为应用的首次启动,然后告诉您的主视图控制器在当前视图顶部添加一个(可能是图片)视图,并设置透明度为0.6

if (figureOutIfIsFirstLaunch)
{
    UIImageView *myOverlay = [...];
    myOverlay.frame = self.view.bounds;
    myOverlay.alpha = 0.6;
    [self.view addSubview:myOverlay];
} 

жҠҠиҝҷдёӘж”ҫеңЁжҲ‘зҡ„applicationDelegateзҡ„application: didFinishLaunchingWithOptions:йҮҢйқўпјҢиҖҢдёҚжҳҜеҢ…еҗ«и§ҶеӣҫжҺ§еҲ¶еҷЁдёӯпјҢдјҡжңүд»Җд№ҲеҗҺжһңеҗ—пјҹ - user

1
Swift 4 更新
 view.isOpaque = false  

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

这个选项在故事板中可用。 确保取消勾选不透明选项 输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接