如何从 UITextField Delegate 获取当前输入的文本?

问题描述

我使用了这个委托方法,但它没有返回我输入的最后一个字符。

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

例如。当前文本字段字符串是“123”,当我输入“4”时,文本字段字符串是“1234”,但上面的委托方法只返回“123”,现在再次输入“5”然后上面的方法返回“1234”,但我期待“12345”

解决方法

但后来我找到了适合我的解决方案

Swift 5

 func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool {
        
        var finalString = ""
        if range.length > 0 {
            finalString = "\(textField.text!.dropLast())"
        } else {
            finalString = "\(textField.text! + string)"
        }
        print(finalString)
        return true
    }