Swift 5 通过在SceneDelegate里面改变rootViewController

2,339 阅读1分钟

oc项目里面设置主控制器

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [UIApplication sharedApplication].delegate.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
        
    [UIApplication sharedApplication].delegate.window.backgroundColor = [UIColor whiteColor];
    
    [UIApplication sharedApplication].delegate.window.rootViewController = [[UIStoryboard storyboardWithName:@"xxxx" bundle:nil] instantiateViewControllerWithIdentifier:@"xxxx"];
    
    [[UIApplication sharedApplication].delegate.window makeKeyAndVisible];
    
    return YES;
}

swift 5项目里面设置主控制器

  • 到SceneDelegate里面
  • 在didFinishLaunchingWithOptions设置是无效的,为什么
  • iOS13之后,Appdelegate不在负责UI生命周期,只负责app的生命周期,所有UI生命周期交给SceneDelegate处理。(在Appdelegate都找不到window),还有一个解决办法,看这里
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    let windowScene = scene as? UIWindowScene

    if let windowScene = windowScene {
        window = UIWindow(windowScene: windowScene)
    }

    window?.frame = (windowScene?.coordinateSpace.bounds)!

    let storyBoard : UIStoryboard = UIStoryboard(name: String (describing: MXTakeAwaysVC.self), bundle:nil)
    
    let rootVC = storyBoard.instantiateViewController(withIdentifier: String (describing: MXBaseNavVC.self)) as! MXBaseNavVC

    window?.rootViewController = rootVC

    window?.makeKeyAndVisible()

    guard let _ = (scene as? UIWindowScene) else { return }
}


---

oc写法
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions  API_AVAILABLE(ios(13.0)){

    UIWindowScene *windowScene = (UIWindowScene *)scene;

    self.window = [[UIWindow alloc] initWithWindowScene:windowScene];

    self.window.frame = windowScene.coordinateSpace.bounds;

    ViewController *control = [[ViewController alloc]init];

    self.window.rootViewController = control;

[self.window makeKeyAndVisible];

}
  • 另外的一个解决思路
    • 1.Declare var window: UIWindow? in your AppDelegate.swift.
    • 2.Remove SceneDelegate.swift from your files.
    • 3.Remove Application Scene Manifest from Info.plist.
    • 4.Use window object in your AppDelegate.swift as you want.