How do I use preference keys to pass values up the view tree in SwiftUI?

In SwiftUI, preference keys provide a way to pass values up the view hierarchy, allowing child views to communicate information back up to their parent views. This can be particularly useful for layouts or scenarios where a child view needs to report information that might influence the layout or behavior of a parent view.

Here’s how you can create a custom preference key and use it to pass values up the view tree:

// Define a preference key struct HeightPreferenceKey: PreferenceKey { typealias Value = CGFloat static var defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } } struct ChildView: View { var body: some View { Text("I have some height!") .padding() .background(Color.blue) .foregroundColor(.white) .overlay( GeometryReader { geometry in Color.clear.preference(key: HeightPreferenceKey.self, value: geometry.size.height) } ) } } struct ParentView: View { @State private var childHeight: CGFloat = 0 var body: some View { VStack { ChildView() .onPreferenceChange(HeightPreferenceKey.self) { value in self.childHeight = value } Text("Child height is: \(childHeight)") .padding() } } }

SwiftUI preference keys data binding view hierarchy