如何以编程方式更改RootViewController?

时间:2014-12-29 11:43:24

标签: ios iphone

我正在开发一些自定义相机应用程序,我只想跳过我的登录页面,并在用户已注册时将我的相机主页设置为初始根视图。我是从AppDelegate或视图代码中进行的,但是我从头开始或任何示例示例中都会出现错误。我的代码如下,

代码位于viewDidLoad

如果我在AppDelegate下面尝试代码,那么它也会出现问题

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main.storyboard" bundle:[NSBundle mainBundle]];

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:@"registered"])
{
    NSLog(@"no user register");

    ViewController *loginview = [storyBoard instantiateViewControllerWithIdentifier:@"ViewController"];
    self.window.rootViewController = loginview;        
}
else
{        
    NSLog(@"user is registered");

    CameraHome *camview = [storyBoard instantiateViewControllerWithIdentifier:@"CameraHome"];
    self.window.rootViewController = camview;
}

如果我已经注册并直接切换到我的主页,任何人都可以请说明如何跳过该视图。

2 个答案:

答案 0 :(得分:1)

in .h file
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *objUINavigationController;

in .m file

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];

if (![defaults boolForKey:@"registered"])
{
ViewController *objViewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];

self.objUINavigationController = [[UINavigationController alloc] initWithRootViewController:objViewController];

[self.window setRootViewController:self.objUINavigationController];

[self.window makeKeyAndVisible];

}
else
{
    CameraHome *camview = [[CameraHome alloc] initWithNibName:@"CameraHome" bundle:nil];

    self.objUINavigationController = [[UINavigationController alloc] initWithRootViewController:camview];

[self.window setRootViewController:self.objUINavigationController];

[self.window makeKeyAndVisible];
}

答案 1 :(得分:0)

-(void)viewWillAppear:(BOOL)animated{
    // check if user is already Logged in
    if([defaults objectForKey:@"username"]!=nil  && ![[defaults objectForKey:@"username"] isEqualToString:@""]){

        UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
        UIViewController *view = [storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];

        [self presentViewController:view animated:YES completion:nil];
    }
}