一般最簡單的方法
UIWindow *window = [UIapplication sharedApplication].keyWindow;或者UIWindow *window = [[UIApplication sharedApplication].windows lastObject];或者再對windows做一下排序判斷
UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) { return win1.windowLevel - win2.windowLevel; }] lastObject];上面不管哪種方法,如果是在只有一個window的情形下倒沒問題,但是當存在多個window,則都不能真正獲取到當前正在顯示的窗口 。終極方法如下:
UIWindow *topWindow = [[[UIApplication sharedApplication] delegate] window];2. 獲取最頂層的視圖控制器
不論中間采用了 push->push->PResent還是present->push->present,或是其它交互
(UIViewController *)theTopviewControler{ UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController; UIViewController *parent = rootVC; while ((parent = rootVC.presentedViewController) != nil ) { rootVC = parent; } while ([rootVC isKindOfClass:[UINavigationController class]]) { rootVC = [(UINavigationController *)rootVC topViewController]; } return rootVC;}3. 獲取最頂層的視圖
拿到視圖控制器,獲取視圖就方便了
新聞熱點
疑難解答