I have a SettingsView to let the user change the color scheme for the app, I store the user selection using @AppStorage, then i adjust the preferredColorScheme for the SettingsView using the value from @AppStorage, everything is working good because I change the view appearance based on the @AppStorage value and not the colorScheme environment property, if i try to do so, it wont work. preferredColorScheme is not being updated when AppStorage value changes, but when i exit the view and open it again.
I have a SettingsView to let the user change the color scheme for the app, I store the user selection using @AppStorage, then i adjust the preferredColorScheme for the SettingsView using the value from @AppStorage, everything is working good because I change the view appearance based on the @AppStorage value and not the colorScheme environment property, if i try to do so, it wont work. preferredColorScheme is not being updated when AppStorage value changes, but when i exit the view and open it again.
For some reason, it is working perfectly on the preview but not in the simulator itself.
import SwiftUI
struct SettingsView: View {
@State private var isPresentPrivacyPolicy = false
@State private var isPresentTermsOfUse = false
@AppStorage("selectedColorScheme") private var selectedColorScheme = "Light"
var body: some View {
ZStack {
if selectedColorScheme == "Dark" {
Theme.darkBackground
.ignoresSafeArea()
} else {
Theme.lightBackground
.ignoresSafeArea()
}
List {
Section {
HStack {
Image(systemName: "doc.text.magnifyingglass")
Button("Privacy Policy") {
isPresentPrivacyPolicy = true
}
.buttonStyle(.plain)
}
HStack {
Image(systemName: "doc.plaintext")
Button("Terms of use") {
isPresentTermsOfUse = true
}
.buttonStyle(.plain)
}
} header: {
Text("About")
.font(.headline)
}
.listRowBackground(selectedColorScheme == "Dark" ? Theme.listDarkBackground : Theme.listLightBackground)
Section {
Picker("Color Scheme", selection: $selectedColorScheme) {
HStack {
Image(systemName: "sun.max")
Text("Light")
}
.tag("Light")
HStack {
Image(systemName: "moon")
Text("Dark")
}
.tag("Dark")
}
} header: {
Text("App")
.font(.headline)
}
.listRowBackground(selectedColorScheme == "Dark" ? Theme.listDarkBackground : Theme.listLightBackground)
}
.scrollContentBackground(.hidden)
}
.preferredColorScheme(selectedColorScheme == "Dark" ? .dark : .light)
.sheet(isPresented: $isPresentTermsOfUse) {
NavigationStack {
WebView(url: URL(string: "example.com")!)
.ignoresSafeArea()
.navigationTitle("App")
.navigationBarTitleDisplayMode(.inline)
}
}
.sheet(isPresented: $isPresentPrivacyPolicy) {
NavigationStack {
WebView(url: URL(string: "example.com")!)
.ignoresSafeArea()
.navigationTitle("App")
.navigationBarTitleDisplayMode(.inline)
}
}
}
}
struct Settings_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}