Thursday, March 7, 2013

Programmatically Adding UINavigationController to existing app in iOS 6 with ARC

Whenever you build an app, you think you know how it should be structured. How are the views going to be layed out for the user to see. However, sometimes designs have to change (Mostly because the client keeps a moving target). How can you add that very helpful Navigation Controller into an existing app quickly and easily...

First, don't panic. It is actually quite easy. the guys at apple feel your pain and tried to make this as confortable as possible. 

In the AppDelegate.m;

    UINavigationController *navCtrlr = [[UINavigationController alloc]initWithRootViewController:self.viewController];
    [self.window setRootViewController:navCtrlr];


Where "self.viewController" is your existing viewController that has your first view. 
Done. 
Thats it. 
Ta Da!

now all you need to do is go through your code and turn the "addSubview" to this;

     [self.navigationController pushViewController:_detailViewController animated:YES];

Where "_detailViewController" is your next view in the stack you want to view. 

As you know, navigationController has a auto back button, but if you want to do it manually;

 [self.navigationController popViewControllerAnimated:YES];

or
 [self.navigationController popToRootViewControllerAnimated:YES];
if you want to go all the way back to the beginning. 

Other quick cosmetic items you can do is;

-(void) viewWillAppear:(BOOL)animated{
    self.title = @"My Title";

    self.navigationController.navigationBarHidden = NO;
}

Which will let you change the title on the NavBar. And make sure it is not hidden.

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
}

Which will let you change the colour of the NavBar. 

There is a lot more that can be done, but I hope that gets you off the ground and in the right direction. 

Here is an add on that looks interesting;
iOS Open Source: Drop-Down Navigation Menu