Detect backspace Event in UITextField

后端 未结 11 589
自闭症患者
自闭症患者 2020-12-04 16:35

I am searching for solutions on how to capture a backspace event, most Stack Overflow answers are in Objective-C but I need on Swift language.

First I have set deleg

11条回答
  •  醉梦人生
    2020-12-04 17:25

    Swift 4: If the user presses the backspace button, string is empty so this approach forces textField to only accept characters from a specified character set (in this case utf8 characters) and backspaces (string.isEmpty case).

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.cString(using: String.Encoding.utf8) != nil {
            return true
        } else if string.isEmpty {
            return true
        } else {
            return false
        }
    }
    

提交回复
热议问题