user2536879
user2536879

Reputation: 187

Objective-C: whose view is not in the window hierarchy

I have this code that works so that once i press a button the view changes in my storyboard:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *viewController = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"view1"];
[self presentViewController:viewController animated:YES completion:nil];

This code work but when i use it again to change back to my original view using:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *viewController = (ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"view2"];
[self presentViewController:viewController animated:YES completion:nil];

It does not work and i receive this error:

Warning: Attempt to present <UIViewController: 0x863ad30> on <UITabBarController: 0x86309b0> whose view is not in the window hierarchy!

The identifies are set and i am not the functions in my viewdidload so i do not know how to fix this.

Can anybody help?

Upvotes: 2

Views: 13725

Answers (3)

aToz
aToz

Reputation: 2464

Try this,

First Method

-(IBAction)signin:(id)sender
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"viewController"];
    [[[[UIApplication sharedApplication] delegate] window] setRootViewController:vc];

}

Second method (to return back to the previous view)

- (IBAction)signout:(id)sender
{

    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"parentViewController"];
    [[[[UIApplication sharedApplication] delegate] window] setRootViewController:vc];

}

Upvotes: 19

Tarek Hallak
Tarek Hallak

Reputation: 18470

This might happen if you call the method before calling makeKeyAndVisible, so move the calling after that.

If not try the hack below:

[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:viewController animated:YES completion:nil];

Upvotes: 5

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

The error message says all: you have to add the view controller's view to the window before presenting the view controller:

UIWindow* keyWindow= [[UIApplication sharedApplication] keyWindow];
[keyWindow addSubview: viewController.view];
[self presentViewController:viewController animated:YES completion:nil];

Upvotes: 1

Related Questions