2013-04-29 75 views
15

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

我有我的整个应用程序完成(这是使用的.xib的,因为它从一年前,但随时在故事板格式,以及解释,因为我可能会重用在其他iOS 5.0+应用此功能)。

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

+1

[相关问题](http://stackoverflow.com/questions/849458/transparent-modal-view-on-navigation-controller/859215#859215),虽然有点过时 – user 2013-04-29 16:12:52

回答

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

就作出这样的数字,如果它是国内首家推出应用程序的机制,然后告诉您的主视图控制器对当前视图顶部添加一个(可能是图像)视点与0.6阿尔法

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

会有什么反响这在我的applicationDelegate的'应用程序:didFinishLaunchingWithOptions:'而不是包含视图的控​​制器? – user 2013-04-29 17:30:40

4

这可以很容易地用UITextView和UIButton完成。只需简单地将UITextView的你要显示的内容在屏幕上,使得它的屏幕的全框的大小,改变背景颜色为黑色背景.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)然后设置 的的backgroundColor为黑色,并设置阿尔法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

,不要忘了阅读的代码下面的注意事项,了解你必须做什么。

+0

虽然这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/评论/低质量/职位/ 10848678) – 2016-01-11 11:06:18

+1

好的,我解决了我的答案 – 2016-01-11 12:02:35