Introduction
In SwiftUI, data generally flows downwards, meaning data is passed from parent views to child views. However, there are situations where you may want to pass data in the opposite direction—from a child view to a parent view.
SwiftUI’s PreferenceKey
protocol is a powerful solution for these cases. PreferenceKey
enables data to travel up the view hierarchy, allowing parent views to access values defined in their child views.
Creating a Custom PreferenceKey
To create a PreferenceKey
, start by defining a new struct that conforms to the PreferenceKey
protocol. This struct must have a defaultValue
and a reduce
function to aggregate multiple values.
struct MyPreferenceKey: PreferenceKey {
static var defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value += nextValue()
}
}
Continue reading
Access to all the content with our plans.
- Junior level content
- Senior level content
- Expert level content
- Extra content
- Question submissions
Be the first to comment