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()
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?