Why is the modifier .navigationBarTitle not applied to NavigationView?

Viewed 2790

In SwiftUI, I understand that modifiers are used to modify a view. When modifying a view, the modifier returns the view wrapped in _ModifiedContent.
When embedding my view inside a NavigationView and assigning a navigation bar title like this: (as seen in Apple's official tutorials)

NavigationView {
    Text("Hello, World!")
        .navigationBarTitle(Text("My first SwiftUI App"))
}

...why is the modifier for the navigation bar title applied to Text, not to NavigationView?

2 Answers

Like Martin linked to, navigationBarTitle only works when contained in NavigationView. This is discussed briefly in the SwiftUI Essentials talk at ~52:30. The title ends up flowing up to the NavigationView, so that views that get pushed can also provide a title of their own (e.g. the view that gets pushed at ~54:00).

If the title was attached to the NavigationView directly, all possible titles would need to be determined up front and removed from the views the titles are associated with.

It's similar to UIViewController's navigationItem property, which is attached to each pushed view instead of the UINavigationController itself.

Because the .navigationBarTitle() is modifier on the View inside of NavigationView, It is not on the NavigationView. And the same is the case for .navigationBarItem(). Please refer to Building Lists and Navigation

Related