Search code examples
uitextfielduitextfielddelegate

Swift 4 how to know delete key is pressed when UITextField becomes first responder?


I've searched for the answer, it's all about using shouldChangeCharactersInRange function of UITextFieldDelegate. It works for most cases. But what if UITextField is already empty,shouldChangeCharactersInRange method is not called any more when click delete button. Any help appreciated.


Solution

  • This can be done using multiple methods(not straight though!). One is to put an invisible button over it, or by subclassing UITextField and adding it as a custom class of the desired textfield. Then override the method deleteBackward. This method will catch all the backspace events.

    Subclass UITextField:

    // MyTextField.swift
    
    import UIKit
    
    protocol MyTextFieldDelegate {
        func textFieldDidDelete()
    }
    
    class MyTextField: UITextField {
    
        var myDelegate: MyTextFieldDelegate?
    
        override func deleteBackward() {
            super.deleteBackward()
            myDelegate?.textFieldDidDelete()
        }
    
    }
    

    Implementation:

    // ViewController.swift
    
    import UIKit
    
    class ViewController: UIViewController, MyTextFieldDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // initialize textField
            let input = MyTextField(frame: CGRect(x: 50, y: 50, width: 150, height: 40))
    
            // set viewController as "myDelegate"
            input.myDelegate = self
    
            // add textField to view
            view.addSubview(input)
    
            // focus the text field
            input.becomeFirstResponder()
        }
    
        func textFieldDidDelete() {
            print("delete")
        }
    
    }