I have a container view implementation that reads preference values from child views:
public struct Reader<Content>: View where Content: View {
public var content: () -> Content
public init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
public var body: some View {
content()
.onPreferenceChange(NumericPreferenceKey.self) { value in
// ...
}
}
}
This works fine until the content passed in to the container view is a Group. At that point the onPreferenceChanged modifier is applied to every child of the group, which leads to bugs in my situation.
One thing I can do is simply put the content in a VStack:
public var body: some View {
VStack(content: content)
.onPreferenceChange(NumericPreferenceKey.self) { value in
// ...
}
}
And that works fine to "Ungroup" before applying the onPreferenceChanged modifier. However, is this best practice? Is there a better way to apply a modifier to content as a whole instead of to each member of a potential group? Is it concerning that I might have an extra VStack in the view hierarchy with this fix?