-->

Bug? UILabel live updating by UITextFieldDelegate

2019-02-28 08:10发布

问题:

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!

回答1:

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
    }
}



回答2:

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
}