如何在当前视图上创build半透明视图图层?

您之前可能已经看到过,它在ScoutMob等消费时尚应用程序中变得非常stream行。 我试图在启动时实现60%的透明视图,这将覆盖我的主屏幕,解释如何使用主屏幕的function并在点击时消失。

我已经完成了我的整个应用程序(它使用的是.xib多年前的版本,但也可以在storyboard格式中进行解释,因为我可能会在其他iOs 5.0+应用程序中重复使用此function。)

我没有任何问题提出单一的意见,但暂时分层叠加一个是我没有直觉的东西。 我会继续研究,并包括任何有用的提示,以防其他人试图做同样的事情。

// 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() 

这可以很容易地用UITextView和UIButton完成。 只需将UITextView放置在屏幕上,并将其显示为全屏大小,然后将背景颜色更改为背景色为.6的黑色背景

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

然后将button作为子视图置于顶部,使其成为屏幕的全帧,并将其设置为0.设置button的操作以隐藏文本视图和button。

例:

 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:方法; 我不确定这些是否是我头顶的正确参数。

只要制定一个机制,如果它是应用程序的第一次启动,然后告诉你的主视图控制器添加一个(可能是图像)视图顶部的当前视图与0.6 alpha

 if (figureOutIfIsFirstLaunch) { UIImageView *myOverlay = [...]; myOverlay.frame = self.view.bounds; myOverlay.alpha = 0.6; [self.view addSubview:myOverlay]; } 
  1. 创buildUIView ,将其命名为( dimBackgroundUIView ),然后将backgroundcolor设置为Black,并将alpha设置为0.1或0.2或….
  2. 添加这两行代码,当你需要调暗背景: [self.view addSubview:dimBackgroundUIView]; [self addConstraintsForDimView]; [self.view addSubview:dimBackgroundUIView]; [self addConstraintsForDimView];
  3. 并添加这两行代码,当你想删除调光背景: if(dimBackgroundUIView) [dimBackgroundUIView removeFromSuperview];
  4. 不要忘记添加dimBackgroundUIView的约束(布局)。

选中此项: iOS显示视图时显示昏暗的背景

不要忘了阅读下面的代码说明,了解你要做什么。