Skip to content

Instantly share code, notes, and snippets.

@Tunous
Created September 14, 2023 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tunous/e323a7e67b5683671cc68f339dfb3e59 to your computer and use it in GitHub Desktop.
Save Tunous/e323a7e67b5683671cc68f339dfb3e59 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
ChildView()
ChildView()
}
.padding()
.overlayPreferenceValue(ViewPreferenceKey.self) { $0 }
}
}
struct ChildView: View {
@State private var showInParent = false
var body: some View {
Toggle("Show in parent", isOn: $showInParent)
.preferenceView {
if showInParent {
Text("👋").font(.system(size: 64))
}
}
}
}
struct ViewPreferenceKey: PreferenceKey {
static var defaultValue: AnyView = AnyView(EmptyView())
static func reduce(value: inout Value, nextValue: () -> Value) {
value = AnyView(VStack {
value
nextValue()
})
}
}
extension View {
func preferenceView(@ViewBuilder view: () -> some View) -> some View {
self.preference(key: ViewPreferenceKey.self, value: AnyView(view()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment