selecting alternative first view controller from story board at application startup

后端 未结 4 1276
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 08:04

I\'ve just started on iOS programming and so far the tutorials and answers I found here have been a great help to move forward. However, this particular problem has been bum

4条回答
  •  醉梦人生
    2020-12-29 09:04

    I have a similar scenario as yours. My application uses a UINavigationController as the root view controller. If the user is logged in, I want to present him/her with NotLoggedInViewController, while if it's logged in I want to show the LoggedInViewController.

    In a storyboard a UINavigationController can only have one child, so you have to be able to programmatically assign another root view controller to it.

    I start by creating a custom navigation controller class, let's name it MyNavigationController. In the storyboard I assign this custom class to the navigation controller object.

    Still in the storyboard, I then model both view controllers, and connect one of them to the navigation controller object. Since I need to be able to access them from my code later on, I assign each of them an identifier using the XCode inspector on the right. These identifiers which can be arbitrary strings, but to things simple I just use the class names.

    Finally I then implement the viewDidLoad method on MyNavigationController class:

    BOOL isLoggedIn = ...;
    
    - (void)viewDidLoad {
      id rootController;
      if (isLoggedIn) {
        rootController = [self.storyboard instantiateViewControllerWithIdentifier:@"LoggedInViewController"];
      } else {
        rootController = [self.storyboard instantiateViewControllerWithIdentifier:@"NotLoggedInViewController"];
      }
      self.viewControllers = [NSArray arrayWithObjects:rootController, nil];
    }
    

提交回复
热议问题