Search code examples
swift4textfieldarkituitextfielddelegatedispatch-queue

textfield extension is not updating text on screen (swfit4)


The extension code below updates the the text but does not update the last letter. So if the word she is type in the textfield the text on the screen only shows sh.

    extension ViewController: UITextFieldDelegate{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    DispatchQueue.main.async {
        self.textNode.textGeometry.string = textField.text!
    }
    return true
}
}

Solution

  • I believe that you need to make your delegate callback like this:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        if let textEntered = textField.text,
            let textRange = Range(range, in: textEntered) {
    
        let updatedText = textEntered.replacingCharacters(in: textRange, with: string)
            print("User Has Entered \(updatedText)")
    
            DispatchQueue.main.async {
                self.textNode.textGeometry.string = updatedText
            }
        }
    
        return true
    }
    

    Hope it helps...