在Appdelegate中以编程方式为Storyboard中的UINavigationcontroller设置rootViewcontroller

11

我在NSUserdefaults中有一个值。 我正在使用storyboard,它嵌入在UINavigationController中。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     if([[NSUserDefaults standardUserDefaults]objectForKey:@"isLoggedIn"]){
         //show home page here
        }else{
           // show login view
        }
}

我也可以使用URL链接来打开这个应用程序

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
         NSString *text = [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

         if(text.length > 0){
           // show home page 

         }else {
          // show settings page
        }

        return YES;
}

请问如何基于获取到的值来设置UINavigationControllerrootViewController?请求帮助,谢谢!

2个回答

35

你可以根据if/else条件使用你的ViewController创建一个UINavigationController对象,并将导航控制器设置为AppDelegate中window的rootViewController属性,如下所示:

LoginViewController *loginController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"loginController"]; //or the homeController
UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:loginController];
self.window.rootViewController = navController;

1
不要忘记调用 [self.window makeKeyAndVisible]; - schmidt9
除非您需要多个窗口并更改显示顺序,否则不应要求使用 makeKeyAndVisible - dispatchMain

2

这是我在代码中使用的内容。

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // Get user preference
 NSString * wxyz=[defaults stringForKey:@"wxyz"];
    //Get value at wxyz field

if ([self isInValidwxyz:wxyz]) {
    //check if wxyz is invalid
    //If wxyz is invalid, write custom code
}
else{
    //if valid, 
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"myStoryBoardiPhone" bundle:nil];
        self.window.rootViewController = [storyboard instantiateInitialViewController];
    }
    else{

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"myStoryBoardiPad" bundle:nil];
        self.window.rootViewController = [storyboard instantiateInitialViewController];;
    }
    [self.window makeKeyAndVisible];
}

然后,通过这个链接进行与导航控制器的实现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接