Introducing View Preferences in SwiftUI
Intro
Apple spent a lot of time talking about @State, @Binding and the Environment, but they didn’t give much attention to View Preferences. In fact they only briefly mention its existence in their SwiftUI Essentials talk from WWDC 2019. Even the documentation isn’t much of a help here with descriptions like ‘No overview available’ and no sample code to demonstrate how it should work. So let’s give View Preferences some well deserved love and give it a proper introduction since it can be very useful.
What are View Preferences?
If you have ever used the environment you know how easy it is to flow information down the View hierarchy, but in some situations you need to be able to flow information upwards. This is what View Preferences are used for. It’s a way to send configuration data up the View hierarchy.
Apple has an excellent use case for View Preferences, the NavigationView. The actual title that is used in the NavigationView is set using the navigationTitle(_:)
View Modifier which is placed somewhere lower in the View hierarchy. The NavigationView will be notified that something has changed and it will use the value to present it in the navigation bar.
struct RootView: View {
var body: some View {
NavigationView {…