SwiftUI PreferenceKey for child-to-parent communication

7941
0

PreferenceKey enables child views to pass data up to ancestors, complementing the typical parent-to-child flow. I define a custom preference key by conforming to PreferenceKey protocol with a defaultValue and reduce method that combines multiple values. Child views set preferences with .preference(key:value:) modifier. Parent views read them with .onPreferenceChange(). Common use cases include measuring child sizes, collecting scroll positions, and building custom layouts. For anchors, Anchor preferences pass geometry information. This pattern enables complex layouts like badges on tab bars or dynamic height containers. PreferenceKeys make SwiftUI layouts more flexible without breaking the declarative paradigm.