Home > Software engineering >  Pass Binding<String> to UserDefaults-Swift
Pass Binding<String> to UserDefaults-Swift

Time:01-29

I created a watchos App that asks the user for his weight and want to store the weight's value in Userdefaults. The code is as follows

...
@State var weight: String = ""
        var body: some View {
                ScrollView{
                VStack(alignment: .leading) {
                    TextField("Enter height...", text: $weight)
                        .onAppear(){
                            UserDefaults.standard.setValue(weight, forKey: "userWeight")}
                            ...
        }
     }

When I read the userdefaults userweight is "".

CodePudding user response:

Maybe I misunderstood your code, but I don't see any reason for why the value of weight will be different then "". You're setting the value in UserDefault upon the appear of the TextField. Add a button and set the value upon clicking it, like in this example:

@State var weight: String = ""
var body: some View {
    ScrollView{
        VStack(alignment: .leading) {
            TextField("Enter height...", text: $weight)
                .onAppear {
                    print("Current value of weight:\(weight)") // you will get here "" as it happens on first appear of the view
                }
            
            Button("Submit") {
                print("Current value of weight:\(weight)") // you will get here the value you typed on the text field
                UserDefaults.standard.setValue(weight, forKey: "userWeight")
            }
        }
    }
}

Alternatively, you can use the onChange modifier, and the value will be modified upon every text change:

@State var weight: String = ""
    
var body: some View {
    ScrollView{
        VStack(alignment: .leading) {
            TextField("Enter height...", text: $weight)
                .onAppear {
                    print("Current value of weight:\(weight)") // you will get here "" as it happens on first appear of the view
                }
                .onChange(of: weight) { newValue in
                    print("Current value of weight:\(weight)") // you will get here the value you typed on the text field
                    UserDefaults.standard.setValue(weight, forKey: "userWeight")
                }
        }
    }
}

and as onChange is available only for iOS14 deployment target, you can use the onReceive instead which is available since iOS13 (don't forget to import Combine for that):

.onReceive(Just(weight)) { newValue in
    print("Current value of weight:\(weight)") // you will get here the value you typed on the text field
    UserDefaults.standard.setValue(weight, forKey: "userWeight")
}
  •  Tags:  
  • Related