Created
September 22, 2022 23:23
-
-
Save christianselig/761c10bfce597c48ab6dda71cba3697c 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 | |
enum ShopState: Int { | |
case iceCream, flowers | |
} | |
struct ShopStatePreferenceKey: PreferenceKey { | |
static var defaultValue: ShopState = .iceCream | |
static func reduce(value: inout ShopState, nextValue: () -> ShopState) { | |
value = nextValue() | |
} | |
} | |
struct ContentView: View { | |
@State var shopState: ShopState = .iceCream | |
var body: some View { | |
ZStack { | |
switch shopState { | |
case .iceCream: | |
IceCreamView() | |
case .flowers: | |
Text("Here are flowers") | |
} | |
} | |
.onPreferenceChange(ShopStatePreferenceKey.self) { value in | |
self.shopState = value | |
} | |
} | |
} | |
struct IceCreamView: View { | |
@State var shopState: ShopState = .iceCream | |
var body: some View { | |
VStack(spacing: 15.0) { | |
Text("Here is ice cream: 🍦 Wanna go see flowers next?") | |
Button { | |
self.shopState = .flowers | |
} label: { | |
Text("See Flowers") | |
} | |
.preference(key: ShopStatePreferenceKey.self, value: shopState) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just move the onPreferenceChange method just under the IceCreamView inside the switch case.