Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the modifier .navigationBarTitle not applied to NavigationView?

Tags:

swift

swiftui

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?

like image 774
LinusGeffarth Avatar asked Jun 08 '19 11:06

LinusGeffarth


People also ask

What is NavigationView?

↳ com.google.android.material.navigation.NavigationView. Represents a standard navigation menu for application. The menu contents can be populated by a menu resource file. NavigationView is typically placed inside a DrawerLayout .

What is the navigation title?

The navigation title is the label that shows in your site's left-hand navigation menu (and the drop-down navigation, if applicable).

How do I change the navigation bar color in SwiftUI?

To change a navigation bar color in SwiftUI, you apply toolbarBackground modifier to the content view of NavigationStack . NavigationView is deprecated in iOS 16. toolbarBackground accepts two parameters. ShapeStyle : The style to display as the background of the bar.

How do I navigate in SwiftUI?

SwiftUI's NavigationLink has a second initializer that has an isActive parameter, allowing us to read or write whether the navigation link is currently active. In practical terms, this means we can programmatically trigger the activation of a navigation link by setting whatever state it's watching to true.


1 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.

like image 200
Taylor Avatar answered Sep 21 '22 07:09

Taylor