What is the preferred container view for creating navigation-based interfaces in SwiftUI for iOS 16 and later?

iOS interview question for Intermediate practice.

Answer

For iOS 16 and later, the preferred container view for creating navigation-based interfaces (push/pop stack navigation) in SwiftUI is NavigationStack. It largely replaces the older NavigationView, offering a more flexible and powerful API, especially for programmatic navigation and state management. Key Features: Stack-Based: Manages a stack of views, where new views are pushed onto the stack and can be popped off to return to previous views. NavigationLink: Used to trigger navigation to a new view when tapped. Value-Based Navigation: Supports navigating based on data (NavigationLink(value: data)), decoupling the link from the specific destination view. Programmatic Control: Allows managing the navigation path (the stack of views or data representing the stack) programmatically using a binding. Customization: Provides modifiers like .navigationTitle() and .toolbar() for configuring the navigation bar. Basic Usage: swift import SwiftUI struct ContentView: View { var body: some View { // Use NavigationStack as the root container NavigationStack { List { NavigationLink("Go to Detail") { DetailView() } // ... other list items ... } .navigationTitle("Main List") } } } struct DetailView: View { var body: some View { Text("This is the Detail View") .navigationTitle("Detail") } } While NavigationView still exists for backward compatibility and specific split-view scenarios (especially on iPadOS/macOS), NavigationStack is the recommended approach for standard stack-based navigation on iOS 16+.

Explanation

NavigationStack uses a stack-based approach, similar to UINavigationController in UIKit, making programmatic control and state restoration more straightforward than the multi-column model sometimes implied by NavigationView.

Related Questions