Skip to content

Instantly share code, notes, and snippets.

@glm4
Created February 23, 2024 15:45
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 glm4/59c8ce10aa983f5a17ad3bf850dad093 to your computer and use it in GitHub Desktop.
Save glm4/59c8ce10aa983f5a17ad3bf850dad093 to your computer and use it in GitHub Desktop.
Dynamic Appearance mode
// 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())
}
}
// 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