Search code examples
ioscocoa-touchinterface-builderuinavigationbar

How to create Navigation bar with back button to the left?


In my app I am trying to navigate from the Second ViewController to the First ViewController using a Navigation Bar Back Button, but while dragging and dropping the navigation bar onto the ViewController in my App's XIB I am just able to get the bar with title.

What am I doing wrong? I am using Xcode 4.6. and .xib files to design the view. Here's What I'm getting now:

Navigation Bar Without Back Button

Here's what I'm looking for:

Navigation Bar with Back Button


Solution

  • add this code in your BUS2AppDelegate.h file

    @interface BUS2AppDelegate : UIResponder <UIApplicationDelegate>
    {
         UINavigationController *navController;   //you have added this code?
    }
    @property (strong, nonatomic) UIWindow *window;
    
    @property (strong, nonatomic) ViewController *viewController;
        @end
    

    and in BUS2AppDelegate.m file

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
         self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
            // Override point for customization after application launch.
        self.viewController = [[BUS2ViewController alloc] initWithNibName:@"BUS2ViewController" bundle:nil];
    
        // View Controller with each Navigational stack support.
        navController = [[UINavigationController alloc]
                         initWithRootViewController:self.viewController];
        self.window.rootViewController = navController;
        [self.window makeKeyAndVisible];
    
        return YES;
    }
    

    add this code in your first view controller

    #import "AAlesund.h"
    
    - (IBAction)secodVCBtnClicked:(id)sender {
    
    
        AAlesund *aAlesund = [[AAlesund alloc] initWithNibName:@"AAlesund" bundle:nil];
    
    self.navigationItem.title = @"Master";
        [self.navigationController pushViewController:aAlesund  animated:NO];
    }
    

    To add title in navigation bar in second view controller add this code

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        UILabel *nav_title1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 10, 220, 25)];
        nav_title1.font = [UIFont fontWithName:@"Arial-BoldMT" size:18];
        nav_title1.textColor = [UIColor whiteColor];
        nav_title1.adjustsFontSizeToFitWidth = NO;
        nav_title1.textAlignment = UITextAlignmentCenter;
        nav_title1.text = @"Detail";
        nav_title1.backgroundColor = [UIColor clearColor];
        self.navigationItem.titleView = nav_title1;
    }
    

    this is the output.

    enter image description here