Search code examples
iosswiftkeyboarduitextfield

Swift: Is there a method for when someone taps a key on the keyboard?


Is there a method I can use for when any button on the keyboard was tapped on the keyboard that puts input into a text field in Swift? How do I do something (For example display an image in the rightView of the UITextField) when any key that puts input in the UITextField (Excluding, for example, keys like caps lock and the emoji / switch language key) is tapped?


Solution

  • You can do it very easily

    Here is the code:

    extension ViewController : UITextFieldDelegate {
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
            let userImageView = UIImageView(image: UIImage(named: "user"))
            userImageView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
            self.txtField.rightViewMode = .always
    
            if let textFieldValue = textField.text,
                let textFieldRange = Range(range, in: textFieldValue) {
                let newText = textFieldValue.replacingCharacters(in: textFieldRange, with: string)
                if newText == "" {
                    textField.rightView = nil
                } else {
                    textField.rightView = userImageView
                }
            }
            return true
    
        }
    }
    

    Output:

    enter image description here

    If you face any difficulties in this so please let me know.