Created
February 23, 2024 15:45
-
-
Save glm4/59c8ce10aa983f5a17ad3bf850dad093 to your computer and use it in GitHub Desktop.
Dynamic Appearance mode
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
// DynamicColorSchemeModifier.swift | |
import Foundation | |
import SwiftUI | |
struct DynamicColorSchemeModifier: ViewModifier { | |
@EnvironmentObject private var settingsStore: SettingsStore | |
// Allows to manage colorScheme independently for any view | |
@State private var colorScheme: ColorScheme? | |
func body(content: Content) -> some View { | |
content | |
.preferredColorScheme(colorScheme) | |
.onLoad { | |
switch settingsStore.darkModeEnabled { | |
case true: | |
colorScheme = .dark | |
case false: | |
colorScheme = .light | |
default: | |
colorScheme = nil | |
} | |
} | |
.onChange(of: settingsStore.darkModeEnabled) { newValue in | |
switch newValue { | |
case true: | |
colorScheme = .dark | |
case false: | |
colorScheme = .light | |
default: | |
colorScheme = nil | |
} | |
} | |
} | |
} | |
extension View { | |
func dynamicColorSchemeSettings() -> some View { | |
modifier(DynamicColorSchemeModifier()) | |
} | |
} |
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
// SettingsStore.swift | |
import Foundation | |
import SwiftUI | |
class SettingsStore: ObservableObject { | |
enum Key { | |
static let darkMode = "DarkModeEnabled" | |
} | |
@AppStorage(Key.darkMode) private(set) var darkModeEnabled: Bool? | |
func setDarkModeEnabled(_ enabled: Bool = true) { | |
darkModeEnabled = enabled | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment