本文介紹如何用簡單的方式,實現這樣一種效果:一個新的全屏ViewController,以modal的方式遮住原來的頁面,但是是半透明的,還可以看到原來的頁面
全屏遮罩
一開始我嘗試這種方法:
YLSLockScreenViewController *lockScreenController = [[YLSLockScreenViewController alloc] init];// 新ViewController lockScreenController.view.backgroundColor = [UIColor clearColor];// 設置背景色為透明 lockScreenController.modalPresentationStyle = UIModalPresentationFullScreen;// 全屏 [self.mainViewController presentViewController:lockScreenController animated:YES completion:nil];
結果整個背景是黑色的,搜索瞭一下,原因是如果新的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];// 背景色透明 }];
代碼比較簡單,需要註意的是,設置背景色透明的那行代碼,需要寫在completion block裡,而且設置的不是controller.view.backgroundColor,而是controller.view.superview.backgroundColor