iOS Navigation View Controller example

Similar to view controllers that can manage views, UINavigationController a specialized view controller that manages other view controllers to provide a hierarchical navigation for the user. Consider an ecommerce app where you have to drill down thru categories to find products can be easily implemented with help of a navigation view controller. A navigation controller can push a new view controller for display and by default provides a back button in the navigation bar to go back to the previous view controller. You can also use the pop method to pop the current view from the stack of views. In this tutorial we are going to learn the following
  • Create a Navigation View controller programmatically
  • Push a new view controller into the current stack
  • Pop the current view from the stack
  • Set the title of the navigation bar based on the current view
  • Add buttons to navigation bar and attach action method
  • Change the back button in the navigation bar
  • Add toolbar buttons with spacing between them
  • Hide the navigation bar
  • Directly manipulate the view controller stack using the setViewControllers method

iOS Navigation View Controller First Screen
iOS Navigation View Controller Second Screen
iOS Navigation View Controller Last Screen
For this example just create a New Project with the empty application template and then create 3 separate view controllers that represent our screens for display.

Interface file for the application delegate - MyNavigationViewAppDelegate.h

#import <UIKit/UIKit.h>
#import "FirstViewController.h"

@interface MyNavigationViewAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navigationController;
@property (strong, nonatomic) FirstViewController *firstViewController;

@end

Implementation file for the application delegate - MyNavigationViewAppDelegate.m

#import "MyNavigationViewAppDelegate.h"

@implementation MyNavigationViewAppDelegate

@synthesize navigationController;
@synthesize firstViewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //create the navigation controller and add the controllers view to the window
    navigationController = [[UINavigationController alloc] init];
    [self.window addSubview:[self.navigationController view]];
    
    //check if the first viewcontroller eixsts, otherwise create it
    if(self.firstViewController == nil)
    {
        FirstViewController *firstView = [[FirstViewController alloc] init];
        self.firstViewController = firstView;
    }
    
    //push the first viewcontroller into the navigation view controller stack
    [self.navigationController pushViewController:self.firstViewController animated:YES];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    //do nothing
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //do nothing
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //do nothing
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    //do nothing
}

- (void)applicationWillTerminate:(UIApplication *)application {
    //do nothing
}

@end

Interface file for the first View - FirstViewController.h

#import <UIKit/UIKit.h>
#import "SecondViewController.h"

@interface FirstViewController : UIViewController

@property (strong, nonatomic) SecondViewController *secondViewController;

@end

Implementation file for the first View - FirstViewController.m

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

@synthesize secondViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    //set the title of the navigation view
    [self.navigationItem setTitle:@"My First View"];
    
    //set the background color of the view
    [self.view setBackgroundColor:[UIColor lightGrayColor]];
    
    //create a right side button in the navigation bar
    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"Next View"
                                    style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(nextScreen:)];
    [self.navigationItem setRightBarButtonItem:myButton];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationController.toolbarHidden = YES;
    [super viewWillAppear:animated];
}

- (void) nextScreen:(id)sender {
    
    //get reference to the button that requested the action
    UIBarButtonItem *myButton = (UIBarButtonItem *)sender;
    
    //check which button it is, if you have more than one button on the screen
    //you must check before taking necessary action
    if([myButton.title isEqualToString:@"Next View"]){
        NSLog(@"Clicked on the bar button");
        
        //if the second view controller doesn't exists create it
        if(self.secondViewController == nil){
            SecondViewController *secondView = [[SecondViewController alloc] init];
            self.secondViewController = secondView;
        }
        
        
        //tell the navigation controller to push a new view into the stack
        [self.navigationController pushViewController:self.secondViewController animated:YES];
        
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Interface file for the second view - SecondViewController.h

#import <UIKit/UIKit.h>
#import "LastViewController.h"

@interface SecondViewController : UIViewController

@property (strong, nonatomic) LastViewController *lastViewController;

@end

Implementation file for the second view - SecondViewController.m

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

@synthesize lastViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
 //set the title of the navigation view
    [self.navigationItem setTitle:@"My Second View"];
    
    //set the background color of the view
    [self.view setBackgroundColor:[UIColor darkGrayColor]];
    
    //for button tags
    int i = 1;
    
    // Show toolbar
    self.navigationController.toolbarHidden = NO;
    
    //Blank space to add between other items
    UIBarButtonItem *itemSpace = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                  target:nil
                                  action:nil];
    
    //bar button item is a button specialized for placement on a UIToolbar
    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
                                   target:self
                                   action:@selector(checkButtonClick:)];
    editButton.tag = i++;
    
    UIBarButtonItem *forwardButton = [[UIBarButtonItem alloc]
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
                                      target:self
                                      action:@selector(checkButtonClick:)];
    forwardButton.tag = i++;
    
    UIBarButtonItem *popView = [[UIBarButtonItem alloc]
                                    initWithTitle:@"Pop this View"
                                    style: UIBarButtonItemStyleBordered
                                    target:self
                                    action:@selector(checkButtonClick:)];
    popView.tag = i++;
    
    //create an array of buttons 
    NSArray *items = [NSArray arrayWithObjects:popView, editButton, itemSpace, forwardButton, nil];
    //add the buttons to the toolbar
    self.toolbarItems = items;
    
    
}

- (void) checkButtonClick:(id)sender {
    
    //get reference to the button that requested the action
    UIBarButtonItem *myButton = (UIBarButtonItem *)sender;
    NSLog(@"Clicked on one of the toolbar buttons");
    
    //check which button it is, if you have more than one button on the screen
    //you must check before taking necessary action
    switch (myButton.tag) {
        case 1: {
            //send an alert message
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Edit Button Click"
                                                              message:@"You clicked on the Edit Button which basically does nothing"
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                                    otherButtonTitles:nil, nil];
            
            [message show];
        }
            break;
            
        case 2:
            
            //if the last view controller doesn't exists create it
            if(self.lastViewController == nil){
                LastViewController *lastView = [[LastViewController alloc] init];
                self.lastViewController = lastView;
            }
            
            {
                //customize the back button, you must set this before pushing the latest view into the stack
                UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle: @"Go Back"
                                                style: UIBarButtonItemStyleBordered
                                                target: nil
                                                action: nil];
            
                [self.navigationItem setBackBarButtonItem: backButton];
            }
            
            //tell the navigation controller to push a new view into the stack
            [self.navigationController pushViewController:self.lastViewController animated:YES];
            break;
            
        case 3:
            //pop the current view from the stack
            [self.navigationController popViewControllerAnimated:YES];
            
        default:
            break;
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    //display navigation bar
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //display toolbar
    self.navigationController.toolbarHidden = NO;
    [super viewWillAppear:animated]; 
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Interface file for the last view - LastViewController.h

#import <UIKit/UIKit.h>

@interface LastViewController : UIViewController

@end

Implementation file for the last view - LastViewController.m

#import "LastViewController.h"

@interface LastViewController ()

@end

@implementation LastViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view.
    
    //set the title of the navigation view
    [self.navigationItem setTitle:@"My Last View"];
    
    //set the background color of the view
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    int i = 1;
    //display toolbar
    self.navigationController.toolbarHidden = NO;
    
    UIBarButtonItem *itemSpace = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                  target:nil
                                  action:nil];
    
    UIBarButtonItem *hideNavigation = [[UIBarButtonItem alloc]
                                       initWithTitle:@"Hide Navigation"
                                       style: UIBarButtonItemStyleBordered
                                       target:self
                                       action:@selector(checkButtonClick:)];
    hideNavigation.tag = i++;
    
    UIBarButtonItem *removeViews = [[UIBarButtonItem alloc]
                                    initWithTitle:@"Close Views"
                                    style: UIBarButtonItemStyleBordered
                                    target:self
                                    action:@selector(checkButtonClick:)];
    removeViews.tag = i++;
    
    NSArray *items = [NSArray arrayWithObjects:hideNavigation, itemSpace, removeViews, nil];
    self.toolbarItems = items;
    
}


- (void) checkButtonClick:(id)sender {
    
    //get reference to the button that requested the action
    UIBarButtonItem *myButton = (UIBarButtonItem *)sender;
    NSLog(@"Clicked on one of the toolbar buttons");
    
    //check which button it is, if you have more than one button on the screen
    //you must check before taking necessary action
    switch (myButton.tag) {
        case 1:
            //hide the navigation bar 
            [self.navigationController setNavigationBarHidden:YES animated:YES];
            break;
            
        case 2:
            
        {
            //Get the current array of View Controllers
            NSArray *currentControllers = self.navigationController.viewControllers;
            
            //Create a mutable array out of this array
            NSMutableArray *newControllers = [NSMutableArray arrayWithArray:currentControllers];
            
            //create an array set of interger indexes
            NSMutableIndexSet *indexes = [NSMutableIndexSet
                                          indexSetWithIndexesInRange:NSMakeRange(1, 2)];
            
            //Remove the objects from the controller array based on the indexes
            [newControllers removeObjectsAtIndexes:indexes];
            
            //Assign the manipulated array to the Navigation Controller with animation
            [self.navigationController setViewControllers:newControllers
                                                 animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Reference

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.