UINavigationController: Stack-Based Screen Management

UINavigationController manages screens like a deck of cards: you push new ones on top and pop them off to go back. It's standard for hierarchical navigation. The footgun is manually changing the stack; always use the provided push/pop methods.
WHY IT EXISTS Apps often need to present information hierarchically. A user starts at a high-level screen, like a list of contacts, and taps an item to see more detail. UINavigationController was created to manage this common "drill-down" user flow, handling the stack of screens and providing standard UI like a navigation bar and back button automatically.
THE MENTAL MODEL Think of UINavigationController as a stack of plates or a deck of cards. Each card is a screen, represented by a UIViewController. You can only see the top card. When you want to show a new screen, you "push" it onto the top of the stack. To go back, you "pop" the top card off, revealing the one underneath. The controller manages this stack for you.
HOW IT WORKS A UINavigationController is a container view controller. You initialize it with a "root" view controller, which is the bottom of the stack. To navigate to a new screen, you call pushViewController(_:animated:), passing in the new view controller instance. This slides the new screen in and adds it to the top of the stack. The navigation controller automatically adds a navigation bar at the top, displaying the current view controller's title and a back button. Tapping the back button or using the edge-swipe gesture automatically calls popViewController(animated:) to remove the top screen from the stack.
WHEN TO USE IT Use UINavigationController for any task-based or hierarchical navigation flow. It's the foundation for many iOS apps. Examples include navigating through a file system, stepping through a multi-screen setup wizard, or drilling down from a list of items to a detail view, like in the Mail, Photos, or Settings apps.
WHEN NOT TO USE IT Avoid it for content that isn't hierarchical. For sibling screens that a user might want to switch between, like different feeds in a social media app, a UITabBarController is a better fit. For presenting temporary, modal content like a compose window or a login form, you should present the view controller modally instead of pushing it onto the navigation stack.
ONE CANONICAL EXAMPLE In a messaging app, the root view controller is the list of conversations. When you tap a conversation, the app creates an instance of a MessageDetailViewController and pushes it onto the navigation stack. The navigation bar now shows the contact's name as the title and a back button. When you're done and tap back, the MessageDetailViewController is popped, and the conversation list is revealed again.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.