Sunday, September 9, 2012

Navigation Controller FROM Another View Controller

Or you may say "Navigation Controller as the second View," or "Navigation Controller's previous view is a ViewController." The purpose of this post is that the NavController is shown after a normal VC or any other views.

Our previous posts about Navigation Controllers only tackle about making it as our very first view. Now, what if you don't want your Navigation Controller as your first view? What if you want your first view to be a View Controller?

1. Create a New Project.

  • If you choose an Empty Application, create a New File, View Controller subclass, connect it to your AppDelegate using xib (MainWindow) or code it in application:didFinishLaunching method in AppDelegate.m
  • Or, you may choose Single View Application, a View Controller class is provided for you, and the View Controller Class is already connected to your AppDelegate Class (this is hasle free).

2. Add a label to your first ViewController (VC), and a button.
When we click the button, it must show a new view with navigation bar.

3. Create another ViewController subclass, name it "SecondViewController," add a label to your second VC just to indicate that the view belongs to the secondVC.

4. Go back to your first VC interface file, import your SecondVC. Add a UINavigationController property and synthesize it in your implementation file.

//.h file
@property (nonatomic, retain) IBOutlet UINavigationController *navController;

//.m file
@synthesize navController;



5. Go to your firstVC's .xib file, drag a Navigation Controller object from the Object's Library to your Placeholder/Object's panel (or you may simply double-click the Navigation Controller object from the Object's Library).

6. Connect your outlet to your NavigationController object.

7. Expand the Placeholders/Objects Panel by clicking the button inside the orange circle, expand the ViewController inside the Navigation Controller object. Change the class of that ViewController with the name of the class we create a while ago. In our case, it was the SecondViewController.

8. After changing the class, you must see that the ViewController is changed to "Second View Controller." This tells us that the SecondVC is the rootViewController of our NavigationController. When the NavigationController is shown, the UI of the SecondVC must be the view inside the NavigationController.

9. Go to your first VC's implementation file. Add an IBAction method to your button and let's add a code that will show the NavigationController with the SecondVC's view in it.

- (IBAction)goToNavigationController:(id)sender {
    [self presentModalViewController:self.navController animated:YES];
}
//Remember to connect your IBAction to your button in your .xib file.

10. And you're done! Hit Run!


No comments:

Post a Comment