Created
September 14, 2023 06:53
-
-
Save Tunous/e323a7e67b5683671cc68f339dfb3e59 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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