1

I'm trying to make a function where when user enter a text in UITextField in the same moment label shows entered text.

How could I make it?

Like:


textField.text = "10"

Label.text = "\(textField.text) smthg" //. (10 smthg)

textField.text = "10.56"

Label.text = "\(textField.text) smthg" //. (10.56 smthg)
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
Ivan Kisin
  • 385
  • 1
  • 3
  • 12
  • you can update the label in this textfield delegate method `func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}` – Keerthaprasanth Ravikumar Mar 01 '18 at 07:52
  • 1
    Possible duplicate of [How do I check when a UITextField changes?](https://stackoverflow.com/questions/28394933/how-do-i-check-when-a-uitextfield-changes) – Alok Nair Mar 01 '18 at 07:54

3 Answers3

7

Implement UITextFieldDelegate and set it to textField.delegate property. From UITextFieldDelegate implement shouldChangeCharactersIn callback method that gets called everytime the user tries to change input in the textfield:

class MyViewController: UIViewController {

    ...

    func viewDidLoad() {
        super.viewDidLoad()

        // set the textField's delegate to self
        textField.delegate = self
    }

}

extension MyViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // to be always updated, you cannot use textField.text directly, because after this method gets called, the textField.text will be changed
        let newStringInTextField = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
        yourLabel.text = "\(newStringInTextField) smthg"
        return true
    }
}

Using arguments of the function you can get a string that will appear in textField and you can set it as text in yourLabel.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
0

You need to implement textfield's delegate method shouldChangeCharactersIn, it will be called when user start typing, delete a character from textfield, click on clear button appear at right side of textfield when there is text in textfield.

Mahendra
  • 8,448
  • 3
  • 33
  • 56
0

You can use Editing Changed Action for that textField

@IBAction func changeText(_ sender: UITextField) {

     Label.text = "\(textField.text) smthg"
}
Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24