Component - Preference keys
This UI component demonstrates how to use Preference Keys in SwiftUI to pass data up the view hierarchy. It allows child views to communicate values to their parent views in a clean and reactive way.
This UI component demonstrates how to use Preference Keys in SwiftUI to pass data up the view hierarchy. It allows child views to communicate values to their parent views in a clean and reactive way.
VStack
├── Text ("Current Value: X")
└── ChildView
└── Button ("Update Value")PreferenceKey in SwiftUI?PreferenceKey is designed to pass data from child views up to parent views in SwiftUI.PreferenceKey with a default value of 0 and a reduce function that sums values?static var defaultValue: Int = 0.inout value, and add nextValue: static func reduce(value: inout Int, nextValue: () -> Int).struct CountKey: PreferenceKey {
static var defaultValue = 0
static func reduce(value: inout Int, nextValue: () -> Int) {
value += nextValue()
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Hello").preference(key: CountKey.self, value: 1)
Text("World").preference(key: CountKey.self, value: 2)
}
.onPreferenceChange(CountKey.self) { print($0) }
}
}PreferenceKey implementation:
struct SizeKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}inout for value to modify it, but here it is a value parameter.PreferenceKey. Which implementation correctly combines widths to find the maximum?inout value, and use value = max(value, nextValue()).Pass the test and this pattern moves unknown