iOS7实现全屏模态半透明页面的效果

jopen 10年前

本文介绍如何用简单的方式,实现这样一种效果:一个新的全屏ViewController,以modal的方式遮住原来的页面,但是是半透明的,还可以看到原来的页面

全屏遮罩

一开始我尝试这种方法:

    YLSLockScreenViewController *lockScreenController = [[YLSLockScreenViewController alloc] init];// 新ViewController        lockScreenController.view.backgroundColor = [UIColor clearColor];// 设置背景色为透明        lockScreenController.modalPresentationStyle = UIModalPresentationFullScreen;// 全屏                    [self.mainViewController presentViewController:lockScreenController animated:YES completion:nil];  
</div> </div>
结果整个背景是黑色的,搜索了一下,原因是如果新的ViewController以全屏的方式,完全盖住了原来的ViewController,那么ios为了节省内存,会自动将原来的ViewController的view给unload掉,所以背景就变黑了:

The “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:

transparent viewcontroller

所以,用全屏的方式可能实现不了,或许需要override原来的ViewController的viewWillDisappear:方法

逐个添加subview

然后,看到另外一个思路,不调用presentViewController:方法,而是将新的ViewController上的view,addSubView到原来的View上:

addSubView

不过这种方法更加不靠谱,因为虽然原来的View是能看到了,但是没有模态的效果

窗口遮罩,并设置背景色为透明

我最后采取的方法,是present一个窗口化的ViewController。但是这个窗口默认的背景色是磨砂不透明的,因此还需要把它的背景色设为透明。这样看起来就像是全屏遮罩一样,但是由于系统不认为新的View是全屏的,所以上一个View也不会被unload

    YLSLockScreenViewController *lockScreenController = [[YLSLockScreenViewController alloc] init];        lockScreenController.modalPresentationStyle = UIModalPresentationFormSheet;// 窗口                    [self.mainViewController presentViewController:lockScreenController animated:YES completion:^(void){            lockScreenController.view.superview.backgroundColor = [UIColor clearColor];// 背景色透明        }];  
</div> </div>
代码比较简单,需要注意的是,设置背景色透明的那行代码,需要写在completion block里,而且设置的不是controller.view.backgroundColor,而是 controller.view.superview.backgroundColor