概念
ios開發中,在當前視圖上再彈出一個視圖(模態視圖)例如登陸視圖,分享視圖,注冊等等。
說明
實現一個簡單的多視圖應用,視圖控制器都會有一個presentViewController方法,用來顯示模態窗口,在一些特別的環境下我們尤其愿意使用這種窗口,例如臨時呈現一些內容時(登錄視圖、分享列表視圖等),所以今天在這里做一下整理。
一、具體設置和使用
1、彈出模態視圖窗口(presentViewController方法)
樣例代碼為:
GreenViewController *greenViewController = [[GreenViewControlleralloc] init];
方法1:
[self presentModalViewController:greenViewController animated:YES];
方法2:
[self presentViewController:greenViewController animated:YES completion:nil];
兩種方法都可以彈出模態視圖窗口,方法2使用了block封裝,如果在動畫彈出模塊窗口后有其它的操作,可以使用些方法,這種方法比較常見。
2、 彈出時的動畫風格(UIModalTransitionStyle屬性)
彈出模態窗口時,如果我們選擇了動畫顯示,那么我們可以通過modalTransitionStyle屬性來設置切入動畫的風格。
** UIModalTransitionStyleCoverVertical** // 底部滑入。
UIModalTransitionStyleFlipHorizontal // 水平翻轉。
UIModalTransitionStyleCrossDissolve // 交叉溶解。
UIModalTransitionStylePartialCurl // 翻頁。
動畫風格不受設備的限制,即不管是iPhone還是iPad都會根據我們指定的風格顯示轉場效果。
3、回收模塊視圖窗口(dismissModalViewControllerAnimated方法)
方法一:
[self dismissModalViewControllerAnimated:YES]
方法二:
[self dismissViewControllerAnimated:YES completion:nil];
4、presentingViewController
presentingViewController是UIViewController的屬性,官方文檔上這么解釋
presentingViewController
The view controller that presented this view controller.
大致意思是:A push B ,B的presentingViewController就是A.
視圖控制容器(View Controller Container)
像UINavgationController
、UITabBarController
、UISplitViewController
等都屬于view controller container這些類的共性是都有一個類型為數組的對象viewControllers
屬性,用于保存一組視圖控制器。view controller container
會有自己默認外觀。
任何view controller container
對象都可以通過viewControllers
屬性來訪問子對象(視圖),而子對象也可以通過navigationController, tabbarController, splitViewController, parentViewController
找到相應的view controller container
。
當應用以模態形式(通過presentViewController: animated: completion:
推出的視圖)顯示一個視圖時,負責顯示的控制器將是view controller container
最頂部的視圖,而負責推出的視圖。如下圖:
A present B,但是B的presentingViewController卻是UITabBarController。
若想讓B的presentingViewController變成A需要設置definesPresentationContext
設置成YES,默認是NO,另外需要將顯示的視圖的modalPresentationStyle
屬性設置為UIModalPresentationCurrentContext
代碼如下:
navController.modalPresentationStyle = UIModalPresentationCurrentContext;
self.definesPresentationContext = YES;
- (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion;
有這么依據描述:
The presenting view controller is responsible for dismissing the view controller it presented. If you call this method on the presented view controller itself, UIKit asks the presenting view controller to handle the dismissal.
大致意思是:A push B,那么A就有責任dismiss B,如果在B中調用[self dismissViewControllerAnimated...]就會A中發送dismiss,最終會由有A進行dismiss,相當于在B中執行[self.presentingViewController dismissViewControllerAnimated...]
注: self為彈出的模塊視圖控制器
更多內容請參見原帖