iOS7實現全屏模態半透明頁面的效果
本文介紹如何用簡單的方式,實現這樣一種效果:一個新的全屏ViewController,以modal的方式遮住原來的頁面,但是是半透明的,還可以看到原來的頁面
全屏遮罩
一開始我嘗試這種方法:
YLSLockScreenViewController *lockScreenController = [[YLSLockScreenViewController alloc] init];// 新ViewController
lockScreenController.view.backgroundColor = [UIColor clearColor];// 設置背景色為透明
lockScreenController.modalPresentationStyle = UIModalPresentationFullScreen;// 全屏[self.mainViewController presentViewController:lockScreenController animated:YES completion:nil]; </pre><a style="text-indent:0px;" title="派生到我的代碼片" href="/misc/goto?guid=4959551733640380764" target="_blank"></a></div></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:
所以,用全屏的方式可能實現不了,或許需要override原來的ViewController的viewWillDisappear:方法
逐個添加subview
然后,看到另外一個思路,不調用presentViewController:方法,而是將新的ViewController上的view,addSubView到原來的View上:
不過這種方法更加不靠譜,因為雖然原來的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];// 背景色透明 }]; </pre><a style="text-indent:0px;" title="派生到我的代碼片" href="/misc/goto?guid=4959551733640380764" target="_blank"></a></div></div> </div>
代碼比較簡單,需要注意的是,設置背景色透明的那行代碼,需要寫在completion block里,而且設置的不是controller.view.backgroundColor,而是 controller.view.superview.backgroundColor本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!相關經驗
相關資訊
相關文檔
目錄