Binding<String> action tried to update multiple times per frame in SwiftUI

Viewed 766

I have a VM that is implemented as follows:

LoginViewModel

class LoginViewModel: ObservableObject {
    
    var username: String = ""
    var password: String = ""
}

In my ContentView, I use the VM as shown below:

 @StateObject private var loginVM = LoginViewModel()
    
    var body: some View {
      
        
        NavigationView {
            
            Form {
                TextField("User name", text: $loginVM.username)
                TextField("Password", text: $loginVM.password)

Every time I type something in the TextField it shows the following message in the output window:

Binding<String> action tried to update multiple times per frame.
Binding<String> action tried to update multiple times per frame.
Binding<String> action tried to update multiple times per frame.

It is a message and not an error.

If I decorate my username and password properties with @Published then the message goes away but the body is rendered each time I type in the TextField.

Any ideas what is going on and whether I should use @Published or not. I don't think I will gain anything from putting the @Published attribute since this is a one-way binding and I don't want to display anything on the view once the username changes.

1 Answers

If I decorate my username and password properties with @Published then the message goes away

This is the correct solution. You need to use @Published on those properties because that is how SwiftUI gets notified when the properties change.

the body is rendered each time I type in the TextField

That is fine. Your body method is not expensive to compute.

I don't think I will gain anything from putting the @Published attribute since this is a one-way binding

You cannot be sure SwiftUI will work correctly (now or in future releases) if you don't use @Published. SwiftUI expects to be notified when the value of a Binding changes, even when a built-in SwiftUI component like TextField causes the change.

Related