Created
January 2, 2020 21:42
-
-
Save humblehacker/e7f025d9cdf5b67021f13ffff0b14abe to your computer and use it in GitHub Desktop.
Demonstrates setting a preference based on an action
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 { | |
WrapperView { | |
VStack { | |
PrefView() | |
PrefView() | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
struct BooleanKey: PreferenceKey { | |
static var defaultValue: Bool = false | |
static func reduce(value: inout Bool, nextValue: () -> Bool) { | |
let next = nextValue() | |
guard value == false else { return } | |
value = next | |
} | |
} | |
struct PrefView: View { | |
@State var pressed: Bool = false | |
var body: some View { | |
Button(action: { self.pressed.toggle() }) { Text(pressed ? "unpress me" : "press me") } | |
.preference(key: BooleanKey.self, value: pressed) | |
} | |
} | |
struct WrapperView<Content>: View where Content: View { | |
var content: () -> Content | |
@State var pressed: Bool = false | |
init(@ViewBuilder content: @escaping () -> Content) { | |
self.content = content | |
} | |
var body: some View { | |
VStack { | |
Text(pressed ? "pressed" : "unpressed") | |
content() | |
} | |
.backgroundPreferenceValue(BooleanKey.self) { value -> AnyView in | |
DispatchQueue.main.async { self.pressed = value } | |
return AnyView(Color.clear) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment