2010-09-14 30 views
20

如何從應用程序委託爲參考獲取當前活動視圖(當前正由用戶查看的主視圖)?如何從應用程序委託獲取iOS應用程序中的活動視圖?

+0

定義 「主視圖」。一次可以在屏幕上顯示多個「UIView」對象(和子類)。你期望得到哪一個? –

+0

假設用戶當前正在屏幕上執行特定操作,我想爲該屏幕的容器視圖獲取視圖控制器 – David

+0

您必須自己跟蹤這一點。與視圖一樣,屏幕上可能有多個視圖控制器處於活動狀態。 –

回答

9

這取決於你的應用程序的設置。

通常情況下,您的應用程序委託將具有一個主視圖控制器屬性,它可以讓您訪問它。

爲了讓您的應用程序代理

MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 

UIView *topView = appDelegate.viewController.view; 

如果您的應用程序在應用程序的委託,你可以做這樣的事情導航控制器屬性。

UIView *topView = appDelegate.navigationController.topViewController.view; 
+0

第三行給我一個錯誤:在'kzAppDelegate'類型的對象上找不到屬性'navigationController' – zakdances

+0

那麼你可能沒有使用導航控制器。看看我的答案中的第二行代碼。 – Randall

+0

不適用於模態瀏覽! – skywinder

0

可以使用[appDelegate.navigationController.topViewController class]登錄類控制器或獲取title屬性知道它是哪一個。

0

希望這可以幫助任何地方你

UINavigationController *navCnt = (UINavigationController *)self.window.rootViewController; 

if([navCnt.topViewController isMemberOfClass:[WebViewController class]]) 
{ 
    return UIInterfaceOrientationMaskAll; 
} 
else 
return UIInterfaceOrientationMaskPortrait; 
32
UIWindow *window = [[UIApplication sharedApplication] keyWindow]; 
UIView *topView = window.rootViewController.view; 
+1

不適用於模態瀏覽! – skywinder

0

的應用程序,你可以得到你的RootViewController的視圖中也是這樣的:

id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate]; 
UIView *rootView = appDelegate.window.rootViewController.view; 
+1

不適用於模態視圖! – skywinder

14

所有頂級答案不與工作模式呈現意見! 使用此代碼來代替:

UIView * topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];

+0

適合我,謝謝:) –

1

我發現這一點,它爲我所有類型的塞格斯和視圖控制器的偉大工程。 (UIViewController *)getTopController {UIViewController * topViewController = [UIApplication sharedApplication] .keyWindow.rootViewController;}};}}}}

while (topViewController.presentedViewController) { 
    topViewController = topViewController.presentedViewController; 
} 

return topViewController; 

}

0

嘗試Eric's answer

+ (UIViewController*) topMostController 
{ 
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController; 

    while (topController.presentedViewController) { 
     topController = topController.presentedViewController; 
    } 

    return topController; 
} 
相關問題