iOS 模态推出半透明 ViewController 实现方法
模态,ViewController,透明, 截图弹窗
最近做项目时,需求通过模态(modal)推出一个截屏的弹窗, 但是推出的模态 VC 背景图虽然设置了透明,但是推出 VC 界面的时候,VC 并没有实现透明的效果,
刚开始执行时的代码如下:
UIViewController *vc = [[[UIViewController alloc] init] autorelease];
vc.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
[self presentModalViewController:vc animated:YES];
通过上述代码实现,可以发现在动画过程中是半透明的,但是动画结束后就看不到下面一个viewController的内容了,变黑色了。
寻找其原因,解释为:
he “problem” is that iOS is very finicky about not wasting memory,
and since the modal view will completely cover the one beneath it,
it doesn’t make much sense to keep it loaded.
Therefore, iOS unloads the view that presents the modal one.
You may check this behavior by implementing -viewWillDisappear: and -viewDidDisappear
有道词典翻译为:
iOS的“问题”是非常讲究不浪费内存,由于模态视图将完全覆盖下面的一个,它没有多大意义保持加载。因此,iOS卸载的观点介绍了模态。你可以检查这个行为通过实现viewwilldisappear:-viewDidDisappear:
也就是说, 当模态推出一个 VC 界面后,下面的界面在去加载是没有多大意义的,所以之前的界面将不在加载,所以没能实现透明的效果.
在 stackoverflow 上有关于推出 VC 透明问题的问答大家可以参考
http://stackoverflow.com/questions/587681/how-to-use-presentmodalviewcontroller-to-create-a-transparent-view/5579145#5579145
但最后通过"简书"搜索,搜索到了关于透明 VC 的问题:
最终实现效果如下:
ScreenShotViewController * shotVC = [ScreenShotViewController new];
//self is presenting view controller
self.definesPresentationContext = YES;
shotVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.4];
shotVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:shotVC animated:YES completion:nil];
参数详解:
- definesPresentationContext
A Boolean value that indicates whether this view controller's view is covered when the view controller or one of its descendants presents a view controller.
一个布尔值,用于显示这个视图控制器的视图是否覆盖当视图控制器或其后代提供了一个视图控制器。
@property(nonatomic, assign) BOOL definesPresentationContext
UIModalPresentationOverCurrentContext style to present a view controller, this property controls which existing view controller in your view controller hierarchy is actually covered by the new content. When a context-based presentation occurs, UIKit starts at the presenting view controller and walks up the view controller hierarchy. If it finds a view controller whose value for this property is YES, it asks that view controller to present the new view controller. If no view controller defines the presentation context, UIKit asks the window’s root view controller to handle the presentation.
The default value for this property is NO. Some system-provided view controllers, such as UINavigationController, change the default value to YES.
当使用 UIModalPresentationCurrentContext 或 UIModalPresentationOverCurrentContext 风格呈现一个视图控制器,该属性控制现有的视图控制器的视图控制器层次结构实际上是由新内容。发生基于上下文的演讲时,UIKit开始呈现视图控制器和走到视图控制器层次结构。如果找到该属性的一个视图控制器,其价值是肯定的,它要求视图控制器的视图控制器。如果没有视图控制器定义了表示上下文,UIKit问窗口的根视图控制器来处理报告。这个属性的默认值是否定的。一些系统提供视图控制器,如UINavigationController,改变默认值为YES。