SpacyRicochet
SpacyRicochet

Reputation: 2279

How to push a viewController before dismissing modal view controller with Storyboards?

While trying out storyboards for one of my projects I came across something for which I don't have a good solution;

I have a navigation-based application which shows a UITableViewController. The tableView is populated with user-created elements. Tapping an element cell brings up the detail view controller. The user can create a new element by tapping a button in the tableView. This brings up a modal view, which will handle the creation.

Now, when a user is done with creating the element and dismisses the modal view controller, I want the user to see the corresponding new detail view controller and not the tableview. But I can't figure out how to achieve this in storyboards.

Does anyone have a good pattern for this?

Current situation

TableView --(tap create)--> creation modal view --(finish creating)--> TableView

Should be

TableView --(tap create)--> creation modal view --(finish creating)--> detail view

Upvotes: 7

Views: 1923

Answers (2)

Mohannad A. Hassan
Mohannad A. Hassan

Reputation: 1648

You can put the creating view controller in a navigation controller and link the creation view controller to the detail view controller as well with a push segue. When you finish creating the data it will direct to an instance of detail view controller.

If you want to navigate back from details view directly to the table view, you can add a property to the details view controller, say @property (nonatomic) BOOL cameFromCreationViewController;. You can set this property in prepareForSegue: in the source view controller. In the details view make your own back button, and when it's tapped, you can do this:

if(self.cameFromCreationViewController){
     [self.presentingViewController dismissViewController];
}
else {
     [self.navigationController popViewController]
}

Upvotes: 1

SpacyRicochet
SpacyRicochet

Reputation: 2279

The best pattern I could come up with, is the same as the old pattern in code.

Add a property (nonatomic, weak) UINavigationController *sourceNavigationController to the modal view controller. When it becomes time to dismiss the modal view controller, add the following code:

DetailViewController *detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
detailViewController.element = newlyCreatedElement;
[[self sourceNavigationController] pushViewController:detailViewController animated:NO];

And to make sure the sourceNavigationController get set properly, add the following code in the prepareForSegue: of the TableView:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"newElementSegue"]) {
        [[segue destinationViewController] setSourceNavigationController:self.navigationController];
    }
}

Upvotes: 0

Related Questions