ios_app/Shared/Services/ThemeManager.swift
2025-08-14 03:59:41 +03:00

54 lines
1.5 KiB
Swift

import SwiftUI
// Enum to represent the three theme options
enum Theme: String, CaseIterable {
case system = "System"
case light = "Light"
case dark = "Dark"
var colorScheme: ColorScheme? {
switch self {
case .system:
return nil
case .light:
return .light
case .dark:
return .dark
}
}
}
// Observable class to manage the theme state
class ThemeManager: ObservableObject {
@AppStorage("selectedTheme") private var selectedThemeValue: String = Theme.system.rawValue
@Published var theme: Theme
init() {
// Read directly from UserDefaults to avoid using self before initialization is complete.
let storedThemeValue = UserDefaults.standard.string(forKey: "selectedTheme") ?? ""
self.theme = Theme(rawValue: storedThemeValue) ?? .system
}
func setTheme(_ theme: Theme) {
self.theme = theme
selectedThemeValue = theme.rawValue
}
// This will be called from the button
func toggleTheme(from currentSystemScheme: ColorScheme) {
let newTheme: Theme
switch theme {
case .system:
// If system is active, toggle to the opposite of the current system theme
newTheme = currentSystemScheme == .dark ? .light : .dark
case .light:
newTheme = .dark
case .dark:
newTheme = .light
}
setTheme(newTheme)
}
}