Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created September 22, 2022 23:23
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 christianselig/761c10bfce597c48ab6dda71cba3697c to your computer and use it in GitHub Desktop.
Save christianselig/761c10bfce597c48ab6dda71cba3697c to your computer and use it in GitHub Desktop.
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()
}
}
@YuriiKruk
Copy link

Just move the onPreferenceChange method just under the IceCreamView inside the switch case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment