How can I get a textDidChange (like for a UISearchBar) method for a UITextField?

后端 未结 7 809
不知归路
不知归路 2020-12-17 15:23

How can I get a textDidChange method for a UITextField? I need to call a method every time a change is made to a text field. Is this possible? Thanks!

7条回答
  •  轮回少年
    2020-12-17 16:00

    Below is what I used Swift 4

    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
        guard let fieldText = textField.text else {
            return false
        }
        // Append the existing textfield text with the new character
        var text = fieldText + string
        // If it is the very first character, textfield text will be empty so take the 'string' and on delete also textfield text get deleted with a delay
        if range.location == 0{
           text = string
        }
        return true
    }
    

提交回复
热议问题