2011年10月28日

parrentViewController, presentingViewController

又遇到一個 5.0 的改變......

參考官方網頁對 parrentViewController 的說明

Prior to iOS 5.0, if a view did not have a parent view controller and was being presented modally, the view controller that was presenting it would be returned. This is no longer the case. You can get the presenting view controller using the presentingViewController property.

嗯,這又怎樣呢?
假設你今天的 view hierarchy 是這樣:

UIViewController (A)
        |
        |  (presentModalView)
        |
        ----> UINavigationController -> UIViewController (B)
                                                              |
                                                              | (presentModalView)
                                                              |
                                                              ----> UIViewController (C)

你想要從 C 一口氣跳回 A 要怎麼做?
(連 call 兩次 dismissModalView 是不行的,B 會被看到...

總之還是先 dump 一下.....
下面這段 code 放在 B 的 viewDidAppear 裡面
    [self presentModalViewController:C animated:YES];
    NSLog(@"self.modalViewController: %@", self.modalViewController);
    NSLog(@"self.parentViewController: %@", self.parentViewController);
    NSLog(@"self.navigationController.modalViewController: %@", self.navigationController.modalViewController);
    NSLog(@"self.navigationController.parentViewController: %@", self.navigationController.parentViewController);
    if ([self respondsToSelector:@selector(presentingViewController)])
    {
        NSLog(@"self.presentingViewController: %@", self.presentingViewController);
        NSLog(@"self.navigationController.presentingViewController: %@", self.navigationController.presentingViewController);        
    }

4.3 的話輸出長這樣:
self.modalViewController: <C: 0x637a8d0="">
self.parentViewController: <UINavigationController: 0x6563250="">
self.navigationController.modalViewController: <C: 0x637a8d0="">
self.navigationController.parentViewController: <A: 0x637d900="">

阿可是 5.0 的話是長這樣:
self.modalViewController: <C: 0x8608eb0>
self.parentViewController: <UINavigationController: 0x860d970>
self.navigationController.modalViewController: <C: 0x8608eb0>
self.navigationController.parentViewController: (null)
self.presentingViewController: <A: 0x85404a0>
self.navigationController.presentingViewController: <A: 0x85404a0>

所以我最後只好這樣寫 -.-
    UIViewController *parrentVC;
    if ([self respondsToSelector:@selector(presentingViewController)])
        parrentVC = self.presentingViewController;
    else
        parrentVC = self.navigationController.parentViewController;
    [parrentVC dismissModalViewControllerAnimated:YES];


附帶一提,如果你確定你是要跳到最外面,那也可以這樣做: (更正,這招只有 5.0 能用 -.-)
[[[[UIApplication sharedApplication] keyWindow] rootViewController] dismissModalViewControllerAnimated:YES];

沒有留言:

張貼留言