Search code examples
iosobjective-ccocoa-touchios6

Add a UINavigationBar to a TableViewController presented modally?


Let's say that I'm trying to create something like the contacts app. I have a TableViewController (TVC) where you select an item and see all the information about it. You can tap on edit and then a TVC with static cells is presented. This same TVC is also used to add a new item.

I currently have a TVC that I'm trying to re-use. When the user is editing my model, I push the TVC into the navigation stack, but when the user is creating a new item I present the TVC modally.

Obviously, when the TVC is pushed automatically it gets a NavigationBar. On the other hand, when I present it modally, I create my own NavigationBar (with buttons and everything else I need) and I add it as a subview. This presents two problems:

  • The NavigationBar is on top of the first cell.
  • The NavigationBar scrolls with the other cells.

For what I've read, this happens because I'm adding the NavigationBar to the TVC itself.
Having a TableView inside a Navigation controller sounded like an option, but without a TVC I can't have static cells on my TableView.

I thought about not re-using my TVC, but I'd still be stuck with the same problem as I need a TVC with a bar on top.

How can I add a NavigationBar to a TVC with static cells when it is presented modally? Is there another way to tackle this problem?

By the way, I'm using storyboards and I'm targeting iOS6+, so I can't use presentModalViewController:


Solution

  • You can always create a UINavigationController with code, then set the existing table view controller as the root view controller. Then you can present the newly created UINavigationController modally.

    With UINavigationController instance, you will have a UINavigationBar added.

    Get the existing UITableViewController from your storyboard by using the method instantiateViewControllerWithIdentifier. Do not forget to set the identifier in your storyboard first by setting the Storyboard ID. For example, below I set the identifier as CategoriesViewController.

    setting Storyboard ID

    Then I can obtain it with the following code:

    UITableViewController *tableViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CategoriesViewController"];
    UINavigationController *navcon = [[UINavigationController alloc] initWithRootViewController:tableViewController];
    [self presentViewController:navcon animated:YES completion:nil];