2009-08-06 17 views
4

我在導航視圖heirarchy的上下文中切換視圖,我希望能夠在切換時確定先前的視圖是在新視圖下推送的內容。如何確定UINavigationControllers中以前的visibleViewController?

我想這在UINavigationControllerDelegate:

(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated 
{ 
    NSLog(@"Switching from %@ to %@", 
     NSStringFromClass([[navigationController visibleViewController] class]), 
     NSStringFromClass([viewController class]) 
    ); 
} 

我得到這個:

2009-08-05 20:05:21.274應用程序名稱[85913:20B]從 開關ManagementScreen至ManagementScreen

不幸的是,在調用「will」之前,它已經在UINavigat的狀態中被換出ionController,使得傳入的viewController始終與UINavigationController上的visibleViewController相同(也是topViewController屬性,這裏沒有演示,但我用相同的代碼嘗試過)。

我想避免擴展導航視圖控制器,老實說,雖然我可以很容易地把一個屬性委託 - 但我想知道如果這種行爲是可能的在現有的框架(似乎應該被調用之前發生在以後發生的地方,但似乎導航控制器的狀態在任一之前被修改)。

謝謝!

+0

僅供參考,使用NSStringFromClass()更簡單; – 2009-08-06 00:33:18

回答

2
- (void)navigationController:(UINavigationController*)nc 
     didShowViewController:(UIViewController*)vc 
        animated:(BOOL)animated 
{ 
    NSLog(@"Switching from %@ to %@", 
    NSStringFromClass([vc class]), 
    NSStringFromClass([[nc.viewControllers objectAtIndex:[nc.viewControllers count]-1] class])); 
} 
+0

好,除非它不總是工作:setViewControllers ::將覆蓋viewControllers屬性,並且如果你彈出到根目錄,你將會忽略數組邊界(這當然很容易避免,但覆蓋控制器堆棧不知道!) – groundhog 2009-08-06 02:38:19

+0

當然,你應該爲它添加警衛,而且你不應該彈出根目錄。至於setViewControllers - 他明確表示他在推動他的案件。 – 2009-08-06 03:18:13

5

我不認爲使用UINavigationControllerDelegate工作,因爲,因爲這個問題指出,由當時的委託調用將被顯示的視圖控制器的答案已經是navigationController.topViewController的價值和navigationController.visibleViewController。

而是使用觀察者。

步驟1.設立觀察員觀看了UINavigationControllerWillShowViewController通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewControllerChange:) name:@"UINavigationControllerWillShowViewControllerNotification" object:self.navigationController]; 

步驟2.創建通知回調(在本例中稱爲viewControllerChange)和使用密鑰在通知用戶信息字典看最後和下一個視圖控制器:

(void)viewControllerChange:(NSNotification *)notification { 
    NSDictionary *userInfo = [notification userInfo]; 
    NSLog(@"Switching from %@ to %@", [[userInfo objectForKey:@"UINavigationControllerLastVisibleViewController"] class], [[userInfo objectForKey:@"UINavigationControllerNextVisibleViewController"] class]); 
} 
+0

這真的有用。但是我找不到有關該通知的任何文檔,是否是私人的?如果我提交應用程序,我會遇到麻煩嗎?使用它? – leolobato 2010-04-24 13:27:22

+1

沒有。不會遇到麻煩。通知是API的核心部分。 Apple在「Cocoa Fundamentals Guide」中的「與對象交流」部分記錄了這一點 – 2010-05-16 02:22:10

+0

感謝您的回答Dan。當UIViewController不在堆棧中時,委託調用非常糟糕。 – 2013-01-27 13:47:34

相關問題