Programmatically set the initial view controller using Storyboards

前端 未结 22 1949
感情败类
感情败类 2020-11-22 15:00

How do I programmatically set the InitialViewController for a Storyboard? I want to open my storyboard to a different view depending on some condition which may

22条回答
  •  忘了有多久
    2020-11-22 15:28

    You can set initial view controller using Interface Builder as well as programmatically.

    Below is approach used for programmatically.

    Objective-C :

            self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    
            UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"]; // 
    
            self.window.rootViewController = viewController;
            [self.window makeKeyAndVisible];
    
            return YES;
    

    Swift :

            self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    
            var objMainViewController: MainViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainController") as! MainViewController
    
            self.window?.rootViewController = objMainViewController
    
            self.window?.makeKeyAndVisible()
    
            return true
    

提交回复
热议问题