Carpetfizz
Carpetfizz

Reputation: 9189

Load view with the navigation controller?

I have an app where my main view is embedded in a navigation controller. From there, buttons push onto other view controllers. This all works fine. However, one of the view controllers it pushes to updates one of the root's values and presents it again. However this time, it only presents the ViewController without the navigation controller, and of course, pressing the button to go back will end in a crash. Hopefully this picture will help understand my issue. The pressing enter thing isn't really a big deal, I just call this function on return of the keyboard.

Code to go back to the main controller:

-(void)createNewMain:(NSString*)newAddress {
    ViewController* newController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];
    newController.labelText = newAddress;
    newController.connected = self.connected;
    [self presentViewController:newController animated:YES completion:nil];  
}

enter image description here

Upvotes: 1

Views: 1298

Answers (3)

Mohannad A. Hassan
Mohannad A. Hassan

Reputation: 1648

The problem is simple, you're presenting the instantiated view controller modally.

Replace

[self presentViewController:newController animated:YES completion:nil];

with

[self.navigationController pushViewController:newController animated:yes];

Also, you can make a segue to do that from the storyboard. When the segue executes, it will create a new instance and will not use the previously created one.

Note: If you really don't need to create a new instance, consider using delegation to exchange information between objects.

Upvotes: 3

Zen
Zen

Reputation: 3117

Use Delegation to pass the expected/required message you want from your Pi Controller to your Root View Controller and set it up according to the message. You don't need to create a new instance of your Root View Controller from there. You can always go back to your root view controller from anywhere in the navigation stack by using

[[self navigationController] popToRootViewControllerAnimated:YES];

Upvotes: 1

Eugene
Eugene

Reputation: 10045

You don't really want to "return" to a new instance of a root controller. What you need to do to properly return to the root controller is to pop all the other ones from the navigation controller's stack like this:

[self.navigationController popToRootViewControllerAnimated:YES];

Upvotes: 1

Related Questions