0

I've searched everywhere and can't seem to find a clear answer on updating a label in real-time.

How do i go about updating a UILabel (real-time) without the use of a button. For example, i have a text field and a UIlabel connected to the view controller.

As soon as the user starts typing in the textfield, the same text is being displayed in real time on the UI label. As a result,this eliminates the use of a button to update the label. How do i go about doing this?

Vinod Kumar
  • 3,375
  • 1
  • 17
  • 35
Geniouse
  • 189
  • 1
  • 4
  • 15

4 Answers4

7

Use the delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    label.text = textField.text
    return true
}
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Anuraj
  • 1,242
  • 10
  • 25
3

You are update your label in textField shouldChangeCharactersInRange Delegate method :

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

      // Update Your label here......

     YourLabel.text = textField.text 
     return true
 }
Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
1

option 1: Directly you can make action of textfield with value changed

enter image description here

@IBAction func textFieldValueChange(_ sender: UITextField) {
        self.label.text = sender.text
    }

option 2: Give Delegate to TextField

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

     label.text = textField.text 
     return true
 }
anshul king
  • 558
  • 4
  • 17
1

step 1:Extend class to UITextFieldDelegate

class ViewController: UIViewController,UITextFieldDelegate

In ViewDidLoad()

Step 2: Add Following code into ViewDidLoad()

txtDemo.delegate = self

txtDemo.addTarget(self, action: #selector(LabelChanged(_:)), for:.editingChanged)

step 3: Make new Function as below:

func LabelChanged(_ sender:Any) {
    lblDemo.text = txtDemo.text
}

Or Also use delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    lblDemo.text = txtDemo.text
    return true
}

Here lblDemo is UILabel outlet and txtDemo is UITextField outlet

Sakir Sherasiya
  • 1,562
  • 1
  • 17
  • 31