Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use textChange event in SwiftUI TextField Component?

As we used UITextField in Swift

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

And TextField in SwiftUI provide

TextField("", text: $input, onEditingChanged: { changed in  
        print("Changed")  
        self.output = "You are typing: " + self.input  
      }, onCommit: {  
        print("Commited")  
        self.output = "You typed: " + self.input  
      })

Changed will print on begin edit and Commited will print on return key press.

Now i m typing ABC

So now the question is

if i want to call any function or process on press of A, what steps i need to do for that ?

like image 280
Pankaj Bhalala Avatar asked Oct 17 '25 18:10

Pankaj Bhalala


1 Answers

you can use this:

import SwiftUI

struct ContentView: View {

@State var txt = ""

var body: some View {
    TextField("Enter txt", text: Binding<String>(
        get: { self.txt },
        set: {
            self.txt = $0
            self.callMe(with: $0)
        }))
        .padding(20)
}

func callMe(with tx: String) {
    print("---> as you type \(tx)")
}
}
like image 77
workingdog support Ukraine Avatar answered Oct 20 '25 08:10

workingdog support Ukraine