Create a modal view with navigation bar and back button

12,112

Solution 1

Just put a Navbar on the new view with a bar button item. Create an action for the bar button item by control dragging from the bar button item to the .h of the view controller. You can then use a delegate and protocol method to tell the first controller when the button has been pressed and have it use [self dismissModalViewControllerAnimated:YES];

So in your second view create a protocol with a method done, like this:

@protocol SecondViewControllerDelegate <NSObject>

-(void) done;

@end

@interface SecondViewController : UIViewController {
    ...
    id delegate;
}

...

@property (nonatomic, assign) id<SecondViewControllerDelegate> delegate;

-(IBAction)done:(id)sender;  //this will be linked to your nav bar button.
@end

then in your action from your button call this:

-(IBAction)done:(id)sender{
   [self.delegate done];
}

Your first view controller will need to implement the protocol <SecondViewControllerDelegate>

then in your first view controller, set it up as a delegate for your second view controller before you segue.

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"Second View Modal Segue Identifier"])
    {
        SecondViewController *viewController = segue.destinationViewController;
        viewController.delegate = self;
    }
}

lastly, catch the done call from the delegate in your first view controller:

-(void) done
{
    [self dismissModalViewControllerAnimated:YES];
}

That's how I have done it. If you don't have a lot of experience with protocols and delegates it may seem confusing at first, but it has worked well for me.

Solution 2

You will need to wrap your right hand side view controller in a new navigation controller. In IB, select it and choose the menu item Editor -> Embed In -> Navigation Controller and IB will show a nav bar which you can customize to your heart's content.

Share:
12,112
Sergey Grischyov
Author by

Sergey Grischyov

St. Petersburg State University graduate. Cocoa Controls contributor.

Updated on June 07, 2022

Comments

  • Sergey Grischyov
    Sergey Grischyov almost 2 years

    I want to create a modal view with the navigation item (right view on my screenshot) and I want it to have a 'back button'. My app is TabBar application and I don't want this view to have a tab bar, but I want to load a previous view (left view on my screenshot) with a segue similar to the type "push". I can only create push segue to provide right navigation back to the view on the left, if it's loaded as a modal view, the NavigationBar & TabBar are gone. Any workarounds for this? Thanks in advance!

    Here's my screenshot