1

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.

yancaico
  • 1,145
  • 11
  • 21

1 Answers1

2

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")
    }

}
chinmayan
  • 1,304
  • 14
  • 13
  • @[chinmayan](https://stackoverflow.com/users/5628642/chinmayan) Thanks. It works. I should be sorry for asking this question. I found a answer similar to yours, but I don't know why I ignored it. I'll be more patient to search and try before asking. – yancaico Jun 01 '18 at 03:43
  • @Ryan.Yuen sure :-) please be patient while searching for an answer next time. May be the verfied answer won't fit into your requirement, but other answers will, go through them too :-) – chinmayan Jun 01 '18 at 05:06