IceCubesApp/Packages/DesignSystem/Sources/DesignSystem/ThemeApplier.swift

69 lines
1.7 KiB
Swift
Raw Normal View History

import SwiftUI
#if canImport(UIKit)
2023-01-17 10:36:01 +00:00
import UIKit
#endif
public extension View {
2023-01-17 10:36:01 +00:00
func applyTheme(_ theme: Theme) -> some View {
modifier(ThemeApplier(theme: theme))
}
}
struct ThemeApplier: ViewModifier {
2023-01-17 10:36:01 +00:00
@ObservedObject var theme: Theme
func body(content: Content) -> some View {
content
.tint(theme.tintColor)
.preferredColorScheme(theme.selectedScheme == ColorScheme.dark ? .dark : .light)
#if canImport(UIKit)
2023-01-17 10:36:01 +00:00
.onAppear {
setWindowTint(theme.tintColor)
setWindowUserInterfaceStyle(theme.selectedScheme)
setBarsColor(theme.primaryBackgroundColor)
}
.onChange(of: theme.tintColor) { newValue in
setWindowTint(newValue)
}
.onChange(of: theme.selectedScheme) { newValue in
setWindowUserInterfaceStyle(newValue)
}
.onChange(of: theme.primaryBackgroundColor) { newValue in
setBarsColor(newValue)
}
#endif
}
#if canImport(UIKit)
private func setWindowUserInterfaceStyle(_ colorScheme: ColorScheme) {
2023-01-17 10:36:01 +00:00
allWindows()
.forEach {
switch colorScheme {
case .dark:
$0.overrideUserInterfaceStyle = .dark
case .light:
$0.overrideUserInterfaceStyle = .light
}
}
}
2023-01-17 10:36:01 +00:00
private func setWindowTint(_ color: Color) {
2023-01-17 10:36:01 +00:00
allWindows()
.forEach {
$0.tintColor = UIColor(color)
}
}
2023-01-17 10:36:01 +00:00
private func setBarsColor(_ color: Color) {
2023-01-17 10:36:01 +00:00
UINavigationBar.appearance().isTranslucent = true
UINavigationBar.appearance().barTintColor = UIColor(color)
}
2023-01-17 10:36:01 +00:00
private func allWindows() -> [UIWindow] {
2023-01-17 10:36:01 +00:00
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
}
2023-01-17 10:36:01 +00:00
#endif
}