![](/img/trans.png)
[英]iOS: After app launched, UIApplication.sharedApplication.keyWindow.rootViewController==nil
[英]Setting the keyWindow rootViewController not working in iOS8
在我的應用程序中,我需要用戶登錄和注銷。 當我希望用戶注銷時,我會刪除他們的憑據然后:
ZSSLogin *login = [self.storyboard instantiateViewControllerWithIdentifier:@"ZSSLogin"];
[[UIApplication sharedApplication].keyWindow setRootViewController:[[UINavigationController alloc] initWithRootViewController:login]];
假設用登錄viewController
替換當前的rootViewController
( viewController
。
在iOS7上,這可以正常工作。 但是,在iOS8中,它將顯示登錄VC一瞬間,但然后返回到tabBarController,就像沒有發生任何事情一樣。
關於發生了什么的任何想法?
我有完全相同的問題,登錄VC將顯示一瞬間,然后返回我的SplitViewController,只有iOS8,iOS7工作正常。
在我的場景中,這只發生在我在注銷之前提交AlertView時,如果我直接更改rootViewController而沒有AlertView它工作正常。
所以我用這個簡單的解決方法修復了它:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
...
// Added a delay to avoid an iOS8 bug, where setting rootViewControler doesn't work after dismissing an AlertView. (For some reason dispatch_after isn't working here)
[self performSelector:@selector(logout) withObject:nil afterDelay:0.5];
...
我的猜測是在iOS8中,OS使用Window或rootViewController來設置和刪除AlertView,存儲對rootViewController的引用,然后在解除AlertView后將rootViewController設置為該引用。 因此,如果您在操作系統將其設置回來之前更改rootViewController,它將替換您的更改。 如果等待半秒直到操作系統完成對rootViewController的更改,問題就解決了。 當然,這是一個假設。
我也遇到了這個問題。 這是AlertView的錯誤。 您可以使用AlertView的另一個名為的Delegate方法: alertView:didDismissWithButtonIndex:
在此方法中調用您的Setting RootViewController
。
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0){
// change Application.keyWindow.rootViewController
}
}
實際上這是一個與iOS 8相關的問題。在iOS 8中,他們將在設置窗口的rootViewController
屬性后保留舊的視圖層次結構。所以我的解決方案是在設置新的rootviewcontroller
之前刪除子視圖。
Apple文檔還說,“根視圖控制器提供窗口的內容視圖。將視圖控制器分配給此屬性(以編程方式或使用Interface Builder)將視圖控制器的視圖安裝為窗口的內容視圖。如果窗口具有在現有的視圖層次結構中,舊視圖在安裝新視圖之前被刪除。“
for (UIView * subView in self.window.rootViewController.view.subviews) {
[subView removeFromSuperview];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.