Hi,
I'm working on my first "real" app, and am trying to get user settings (stored using AppStorage) to update other views but it only works sometimes.
For example, I have a clock on one screen and showSeconds as an option. This is working fine (with a few seconds of delay to update the view).
SettingsView
@AppStorage("showSeconds") var showSeconds: Bool = true
TimeView
import SwiftUI
struct TimeView: View {
@State var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@State var timeNow = ""
let defaults = UserDefaults.standard
let dateFormatter = DateFormatter()
var body: some View {
@State var showSeconds = defaults.bool(forKey: "showSeconds")
if showSeconds == true {
Text(timeNow)
.font(.extraLargeTitle)
.onReceive(timer) { _ in
self.timeNow = dateFormatter.string(from: Date())
}
.onAppear(perform: {dateFormatter.dateFormat = "h:mm:ss a"})
} else {
Text(timeNow)
.font(.extraLargeTitle)
.onReceive(timer) { _ in
self.timeNow = dateFormatter.string(from: Date())
}
.onAppear(perform: {dateFormatter.dateFormat = "h:mm a"})
}
}
}
But this test example does not.
SettingsView
@AppStorage("showIcon") var showIcon: Bool = true
TestView
import SwiftUI
struct TestView: View {
let defaults = UserDefaults.standard
var body: some View {
@State var showIcon = defaults.bool(forKey: "showIcon")
if showIcon == true {
Image(systemName: "sun")
} else {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
}