18
votes

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
It is documented: developer.apple.com/documentation/swiftui/view/…: “This modifier only takes effect when this view is inside of and visible within a NavigationView.”Martin R
Yes, I've read that but I feel like it doesn't make sense logically, considering the modifier modifies the view it's applied on and the nav bar title has literally nothing to do with the Text object.LinusGeffarth
You can even set it somewhere deeper in the view hierarchy (i.e. on a Spacer in a Toggle in a VStack ...) I have no idea why it works that way.Martin R

2 Answers

10
votes

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.

5
votes

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