A commenting trick that I use
You’ve stumbled into one of the tricky things about building user interfaces with SwiftUI: figuring out which view you’ve attached a method call to.
I didn’t want to clutter the code in the book or confuse people, but I sometimes find myself adding comments to the closing braces of views, so I know which closing brace belongs to which view, like this:
var body: some View {
NavigationView {
List {
Text("Walk the dog")
Text("Brush my teeth")
Text("Learn iOS development")
Text("Soccer practice")
Text("Eat ice cream")
} // List
.navigationBarTitle("Checklist")
} // NavigationView
}
I find that adding these comments, especially when the view starts getting complicated, makes it easier to figure out which view I’m working with. In the code above, it’s a lot easier to see that the call to navigationBarTitle() is attached to the List and not the NavigationView.
(I may have to add this trick to the update of the book!)
Why the title belongs to the List and not the NavigationView
Take a look at this graphic. It’s a screenshot of the app, with the NavigationView and the List highlighted.
The NavigationView is an invisible container that lets you create views that the user can navigate between. You’ll eventually use it to jump from a list view to another view that shows the details of the list item that the user tapped on, and the NavigationView will automatically provide a “Back” button to return to the list view with you having to write any code!
Since navigating between screens involves changing the view inside the NavigationView, it’s up to the view inside the NavigationView to set the title that appears in the navigation bar.
Hope this helps! If you have any more questions, please feel free to ask away.