Search code examples
iosobjective-cuinavigationcontrollersegue

When I should use Navigation Controller?


I don't know when I should use Navigation Controller instead of use segue with normal View Controller? And if use segue, which different between Modal and Push segue?

Can you give me an example?


Solution

  • Short answer: Use a Navigation Controller with "show" segues only to implement DRILL DOWN behavior.

    For example, Navigation Controller → Authors → Books → Book

    • For each level below the "root" (Authors), the Navigation Controller automatically adds the title bar and back button. So on Books, the back button is automatically named "<Authors".

    • The child View Controllers must be connected with SHOW segues -- show segues tell the Navigation Controller "this is a parent-child relationship" and cause the expected slide-in-from-the-right transition. (To jump outside the hierarchy, for example, Books → Login, use a modal segue instead.)

    • The root View Controller has a navigation bar that you can add more bar buttons to, but child View Controllers don't, because it's added automatically.

    FoodTracker Example

    Now the odd-seeming layout of the FoodTracker tutorial in Apple's Start Developing iOS Apps (Swift) can be explained. **What's up with that second nested Navigation Controller? It's just a simple list of meals: tap a meal to show it in Meal Detail, or tap Add to and Meal Detail becomes Add Meal.

    FoodTracker Storyboard

    • The first Navigation Controller makes My Meals the root of the drill-down hierarchy for any number of views "pushed" from there on (no further Navigation Controllers are needed just to do that).

    • But, Meal Detail is used for both displaying an existing meal and adding a new meal. To add a new meal, Cancel and Save buttons are needed. The second Navigation Controller allows those buttons to be added (see 3rd point above) by making Meal Detail a root.

    • Displaying an existing meal is a push segue, but adding a meal is a modal segue (a new meal isn't a drill-down). This is important: the reason Add Meal can't just be pushed is that the automatic back button ("< My Meals") becomes ambiguous: does it save or cancel?

    Because "navigation" and "push" are very general terms, and because it's nice to get a free back button, it's tempting to think Navigation Controllers are to go from anywhere to anywhere, but the behavior is intended just for hierarchical traversal.

    (This is an old question but I was also confused about this as an iOS n00b and like the OP I still had questions.)