Bug? UILabel live updating by UITextFieldDelegate is off by one character

风流意气都作罢 提交于 2019-12-02 10:39:13

问题


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
}


来源:https://stackoverflow.com/questions/44961748/bug-uilabel-live-updating-by-uitextfielddelegate-is-off-by-one-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!