1

Here is a sample app to demonstrate the issue that I ran into:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var aTextLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        aTextField.delegate = self
    }

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

Here is a demo:

Link to Animated Gif

My question is, how to make it such that the label is exactly synced with what I type in the textfield? Thanks!

2 Answers2

2

Rather than using delegate method shouldChangeCharactersIn, you can use EditingChanged as follows.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var aTextLbl: UILabel!
    @IBOutlet weak var aTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func editingChanged(_ sender: UITextField) {
        aTextLbl.text = aTextField.text
    }
}

enter image description here

Lawliet
  • 3,438
  • 2
  • 17
  • 28
  • Thanks for the quick response! Could you be a little more specific, I couldn't find a function that has the keyword "EditingChanged". Thanks! –  Jul 07 '17 at 02:47
  • Updated my answer. – Lawliet Jul 07 '17 at 02:53
  • I tried the "Value Changed" earlier today and it didn't work. But "Editing Changed" works really great! Thank you! –  Jul 07 '17 at 02:59
0

You can do this using UITextFieldDelegate function as well.

You need to manually append string with textField.text value like below:

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

    let currentText = txtFldPassword.text
    let newText = (currentText! as NSString).replacingCharacters(in: range, with: string)
    print(newText)

    return true
}
Surjeet Singh
  • 11,691
  • 2
  • 37
  • 54