Search code examples
iosuikit

Is there a way to track character remove in empty uitextfield?


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

is not invoked when textfield is already empty and back button is pressed

I want to resign first responder and make previous uitextfield in the view become first responder

is there a way to achieve that?


Solution

  • In order to achieve what you want you have to subclass the UITextField and create a custom protocol which will notify you every time the delete is pressed:

    protocol CustomTextFieldDelegate: AnyObject {
        func deleteBackwardPressed()
    }
    
    class CustomTextField: UITextField {
    
        weak var deleteDelegate: CustomTextFieldDelegate?
    
        override func deleteBackward() {
            super.deleteBackward()
            deleteDelegate?.deleteBackwardPressed()
        }
    }
    

    When creating your UIViewController it should conform to the CustomTextFieldDelegate. Also do not forget to assign the delegate to your custom textfield. A simplified ViewController would look something like this:

    class ViewController: UIViewController, CustomTextFieldDelegate {
        private var isTextFieldEmpty = false
        private let customTextField = CustomTextField()
    
        override func viewDidLoad() {
             super.viewDidLoad()
             customTextField.deleteDelegate = self
        }
    
        func deleteBackwardPressed() {
            if isTextFieldEmpty {
                customTextField.resignFirstResponder()
            } else {
                isTextFieldEmpty = customTextField.text?.count == 0
            }
        }
    }