Home > Mobile >  Missing last character with SwiftUI Textifeld
Missing last character with SwiftUI Textifeld

Time:10-15

I just ran into a pretty awkward issue while using a TextField() in SwiftUI. All I'm trying to do is to pass the data from the textfield to a class (that's marked with @ObservableObject). In this class, there's a function called displayData() that just prints out the data that got passed by the textfield. I'd say 70% of the time, the last character of the string is missing. What bugs me here is that it doesn't occur all the time. It makes it pretty hard to figure it out.

To give you an example, if I type 1234 say in the first TextField(), print(self.username) will return 123. When I try to add a second 4, it prints out 12344.

Both the TextField() and the SecureField() are having this problem.

That's what's going on int the ContentView

            TextField("Enter your username here.", text: self.$dataManager.username)
                .padding()
            SecureField("Enter your password here.", text: self.$dataManager.password)
                .padding()
            Spacer()
            Button(action: {
                self.dataManager.displayData()
            }, label: {
                Text("Send Data")
            }).padding()
            Spacer()

And in the class:

var username: String = ""
var password: String = ""

func displayData(){
        print("USERNAME: \(self.username), PASSWORD: \(self.password)")
    }

Thank you very much!

CodePudding user response:

In order for your username and password properties to correctly bind to your fields, you need to annotate them with @Published in your ObservableObject.

The following version works and doesn't suffer from the issues you mention:

class ViewModel : ObservableObject {
    @Published var username = ""
    @Published var password = ""
    
    func displayData(){
        print("USERNAME: \(self.username), PASSWORD: \(self.password)")
    }
}

struct ContentView : View {
    @StateObject var dataManager = ViewModel()
    
    var body: some View {
        TextField("Enter your username here.", text: self.$dataManager.username)
            .padding()
        SecureField("Enter your password here.", text: self.$dataManager.password)
            .padding()
        Spacer()
        Button(action: {
            self.dataManager.displayData()
        }, label: {
            Text("Send Data")
        }).padding()
        Spacer()
    }
}
  • Related