Created
May 23, 2024 10:57
-
-
Save eunjin3786/083137bb69f6598a80ff7b71a41dcfdb 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
✅ 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