Skip to content

Instantly share code, notes, and snippets.

@eunjin3786
Created May 23, 2024 10:57
Show Gist options
  • Save eunjin3786/083137bb69f6598a80ff7b71a41dcfdb to your computer and use it in GitHub Desktop.
Save eunjin3786/083137bb69f6598a80ff7b71a41dcfdb to your computer and use it in GitHub Desktop.
✅ struct KeyColorPreferenceKey: PreferenceKey {
static var defaultValue: Color = .white
static func reduce(value: inout Color, nextValue: () -> Color) {
value = nextValue()
}
}
struct ContentView: View {
@State private var keyColor = Color.white
var body: some View {
VStack {
SettingsView()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(keyColor)
✅ .onPreferenceChange(KeyColorPreferenceKey.self) {
keyColor = $0
}
}
}
struct SettingsView: View {
var body: some View {
ScreenSettingsView()
}
}
struct ScreenSettingsView: View {
var body: some View {
KeyColorSettingsView()
}
}
struct KeyColorSettingsView: View {
@State private var color: Color = .white
var body: some View {
VStack {
Button(
action: {
color = .yellow
},
label: {
Text("YELLOW")
}
)
Button(
action: {
color = .red
},
label: {
Text("RED")
}
)
}
✅ .preference(key: KeyColorPreferenceKey.self, value: color)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment