I organized some settings to be stored in UserDefauls in a struct like this, because I want to have them in one place and to have getters and Setters.
enum PrefKeys : String {
case KEY1
case KEY2
var key: String { return self.rawValue.lowercased()}
}
struct Preferences {
@AppStorage(PrefKeys.KEY1.key) private var _pref_string_1 = ""
@AppStorage(PrefKeys.KEY1.key) var pref_string_2 = ""
var pref_string_1: String {
set { _pref_string_1 = newValue.lowercased() }
get { return _pref_string_1.lowercased() }
}
}
using it like this works fine:
struct ContentView: View {
var p = Preferences()
var body: some View {
NavigationView{
VStack(alignment: .leading){
Text("pref_string_1: \(p.pref_string_1)")
Text("pref_string_2: \(p.pref_string_2)")
NavigationLink("Sub",destination: SubView())
}
}
.padding()
}
}
If I use p as a @State var, it does not update the view, when the @State var is changed:
struct SubView: View {
@State var psub = Preferences()
@AppStorage("standalone pref") private var standalonePref = ""
var body: some View {
VStack(alignment: .leading){
Text("Preference1 in struct: \(psub.pref_string_1)")
TextField("Preference1 in struct:", text: $psub.pref_string_1)
Text("standalonePref \(standalonePref)")
TextField("standalonePref:", text: $standalonePref)
}
}
}
How can I fix this?