有没有一种方法可以将深色主题更改为浅色主题,反之亦然,就像在 swift UI 中以编程方式使用切换一样?
Is there a way to change dark to light theme and vice versa just like using a toggle programmitically in swift UI?
我这样做了,但是整个 contentView 正在再次加载并且应用程序正在进入开始屏幕。
struct ThemeChangeDemoApp: App {
@AppStorage("theme") var currentThemeRawValue: String = "dark"
var body: some Scene {
WindowGroup {
switch currentThemeRawValue {
case Theme.dark.rawValue:
ContentView().environment(\.colorScheme, .dark)
case Theme.light.rawValue:
ContentView().environment(\.colorScheme, .light)
default:
ContentView().environment(\.colorScheme, .dark)
}
}
}
}
从这里开始,我正在更改主题。我将枚举的原始值保存为“深色”或“浅色”。
struct Settings: View {
var body: some View {
Button {
let currentTheme = UserDefaultsHelper.getCurrentTheme()
switch currentTheme {
case Theme.dark.rawValue:
UserDefaultsHelper.saveTheme(theme: .light)
case Theme.light.rawValue:
UserDefaultsHelper.saveTheme(theme: .dark)
default:
UserDefaultsHelper.saveTheme(theme: .light)
}
} label: {
Text("Toggle theme")
}
}
}
WindowGroup {
switch currentThemeRawValue {
case Theme.dark.rawValue:
ContentView().environment(\.colorScheme, .dark)
case Theme.light.rawValue:
ContentView().environment(\.colorScheme, .light)
default:
ContentView().environment(\.colorScheme, .dark)
}
}
switch 语句意味着 SwiftUI 正在使用条件内容填充视图,因此如果值更改,它将重建整个层次结构。你只想改变环境值本身,所以这样的事情可能会更好:
WindowGroup {
ContentView()
.environment(\.colorScheme, currentThemeRawValue == "dark" ?? .dark : .light)
}
我这样做了,但是整个 contentView 正在再次加载并且应用程序正在进入开始屏幕。
struct ThemeChangeDemoApp: App {
@AppStorage("theme") var currentThemeRawValue: String = "dark"
var body: some Scene {
WindowGroup {
switch currentThemeRawValue {
case Theme.dark.rawValue:
ContentView().environment(\.colorScheme, .dark)
case Theme.light.rawValue:
ContentView().environment(\.colorScheme, .light)
default:
ContentView().environment(\.colorScheme, .dark)
}
}
}
}
从这里开始,我正在更改主题。我将枚举的原始值保存为“深色”或“浅色”。
struct Settings: View {
var body: some View {
Button {
let currentTheme = UserDefaultsHelper.getCurrentTheme()
switch currentTheme {
case Theme.dark.rawValue:
UserDefaultsHelper.saveTheme(theme: .light)
case Theme.light.rawValue:
UserDefaultsHelper.saveTheme(theme: .dark)
default:
UserDefaultsHelper.saveTheme(theme: .light)
}
} label: {
Text("Toggle theme")
}
}
}
WindowGroup {
switch currentThemeRawValue {
case Theme.dark.rawValue:
ContentView().environment(\.colorScheme, .dark)
case Theme.light.rawValue:
ContentView().environment(\.colorScheme, .light)
default:
ContentView().environment(\.colorScheme, .dark)
}
}
switch 语句意味着 SwiftUI 正在使用条件内容填充视图,因此如果值更改,它将重建整个层次结构。你只想改变环境值本身,所以这样的事情可能会更好:
WindowGroup {
ContentView()
.environment(\.colorScheme, currentThemeRawValue == "dark" ?? .dark : .light)
}