在研發中總會遇到一些莫名的需求,本著存在即合理的態度跟大家分享一下"模態Model視圖跳轉和Push視圖跳轉的需求實現".
1.連續兩次模態Model視圖之后,然后返回首頁(A -> B -> C -> A)
①效果圖展示:
776982-20161226155053773-531129180.gif
②實現思想解讀:
一開始大家的思維肯定是一層一層的推出控制器,對這是最直接的辦法,但是Apple的工程師思維非同凡響,其實你只需要解散一個Modal View Controller就可以了;即處于最底層的View Controller,這樣處于這個層之上的ModalView Controller統統會被解散;那么問題在于你如何獲取最底層的View Controller,如果是iOS4.0,你可以使用parentViewController來獲得當前Modal ViewController的“父View Controller”并解散自己;如果是iOS 5,你就得用presentingViewController了;
③核心代碼展示:
/** 在C頁面的DisMiss方法里面添加一下代碼(iOS5.0) */
if ([self respondsToSelector:@selector(presentingViewController)]) {
[self.presentingViewController.presentingViewController dismissModalViewControllerAnimated:YES];
} else {
[self.parentViewController.parentViewController dismissModalViewControllerAnimated:YES];
}
/** 在C頁面的DisMiss方法里面添加一下代碼(iOS6.0+) */
if ([self respondsToSelector:@selector(presentingViewController)]){
[self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
else {
[self.parentViewController.parentViewController dismissViewControllerAnimated:YES completion:nil];
}
2.在模態Model推出的視圖中Push下一個帶導航欄的視圖,然后返回首頁(A -> B ->C -> A)
①效果圖展示:
776982-20161226155333867-2139190975.gif
②實現思想解讀:
如果沒有UINavigationController導航欄頁面之間切換是不能實現Push操作的,那我們平時見得無導航欄Push到下一頁是怎么實現的呢? 現在跟大家分享一下實現原理, 就是在第一次Model出來的控制器提前包裝一個導航欄,并在Model出來控制器實現UINavigationController的代理方法,UINavigationControllerDelegate判斷當前Model出來的控制器是否為自身控制器,這樣做的目的就是為了更安全的隱藏該隱藏的控制器導航欄;雖然導航欄隱藏了,但是作為導航欄的屬性還是存在的,所以我們現在就可以不知不覺得在Model出來的控制器里面Push出下一個頁面,而且下一個頁面還是帶導航欄的,這樣Push出來的控制器,不僅沒有消失原有的Pop功能操作,而且還可以實現DisMiss操作;
③核心代碼展示:
/** 這里用到的核心處理辦法是 */
/** 1.在A控制器模態Model推出B控制器的時候先給B控制器包裝一個導航控制器 */
UINavigationController *ANavigationController = [[UINavigationController alloc] initWithRootViewController:[[BViewController alloc] init]];
[self presentViewController:ANavigationController animated:YES completion:nil];
/** 2.在B控制器遵守UINavigationControllerDelegate實現代理協議,隱藏當前控制器的導航欄 */
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
// 判斷要顯示的控制器是否是自身控制器
BOOL isShowMyController = [viewController isKindOfClass:[self class]];
[self.navigationController setNavigationBarHidden:isShowMyController animated:YES];
}
#pragma mark - Push出C控制器
[self.navigationController pushViewController:[[CViewController alloc] init] animated:YES];
/** 3.在C控制器里面可直接在返回按鈕方法里DisMiss */
[self.navigationController dismissViewControllerAnimated:YES completion:nil];