新建了一個(gè)工程使用下面獲取rootVC用來(lái)彈窗時(shí)幔崖,彈出不來(lái),發(fā)現(xiàn)RootViewControlle是nil
UIViewController *RootViewController()
{
id<UIApplicationDelegate> delegate= [UIApplication sharedApplication].delegate;
if([delegate respondsToSelector:@selector(window)]){
UIWindow *window = [(NSObject *)delegate valueForKey:@"window"];
UIViewController *controller = window.rootViewController;
while (controller.presentedViewController) {
controller = controller.presentedViewController;
}
return controller;
}
return nil;
}
需要?jiǎng)h除 SceneDelegate 使用 AppDelegate
Xcode11之后新創(chuàng)建的工程會(huì)多出兩個(gè)文件SceneDelegate扎唾。那么我們?nèi)绾巫屗兓刂暗哪菢拥墓こ棠亍?/p>
一、將這兩個(gè)文件刪除。
會(huì)報(bào)錯(cuò)There is no scene delegate set. A scene delegate class must be specified to use a main storyboard file.
二尽超、將Info.plis 的 UIApplicationSceneManifest 刪除
三额嘿、將AppDelegate.m中的UISceneSession lifecycle注釋掉或者刪掉贸营。
四、在AppDelegate.h加入window岩睁。在didFinishLaunchingWithOptions中加入U(xiǎn)IWindow钞脂。
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
self.window.rootViewController = [[ViewController alloc] init];;
[self.window makeKeyAndVisible];
return YES;
}
刪除后繼續(xù)報(bào)錯(cuò) whose view is not in the window hierarchy .我是demo里面遇到的,在viewDidLoad彈一個(gè)alertViewController捕儒,所以移到外面就好了
- 在 一個(gè) ViewController 里面調(diào)用另外一個(gè) ViewController 是出現(xiàn)這個(gè)錯(cuò)誤:
該錯(cuò)誤一般是由于在 viewDidLoad 里面調(diào)用引起的冰啃,解決辦法是轉(zhuǎn)移到 viewDidAppear 方法里面
- 在 AppDelegate.m 中調(diào)用遇到這個(gè)錯(cuò)誤
解決辦法1:
UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topRootViewController.presentedViewController)
{
topRootViewController = topRootViewController.presentedViewController;
}
//[topRootViewController presentViewController:yourController animated:YES completion:nil];
//or
[topRootViewController myMethod];
解決辦法2:
UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
LoginViewController* loginViewController = [mainstoryboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
[self.window makeKeyAndVisible];
//[LoginViewController presentViewController:yourController animated:YES completion:nil];
//or
[LoginViewController myMethod];