Home > Blockchain >  UITextField: resign keyboard after clearButton is pressed
UITextField: resign keyboard after clearButton is pressed

Time:12-08

I have a UITextfield in a storyboard.

ClearButton is set to 'is always visible'

searchTextField.addTarget(self, action: #selector(searchTextFieldDidChange(textField:)), for: .editingChanged)

When the text field changes, this method is called

@objc func searchTextFieldDidChange(textField: UITextField){
    if textField.text == "" {
        textField.resignFirstResponder()
    }
    fireSearch()
}

When I clear the text field using backspace, textField.resignFirstResponder() is called, the keyboard vanishes as I want it.

When I clear the text field using the clear button, textField.resignFirstResponder() is called, the keyboard vanishes and appears again immediately.

What can I do that the keyboard keeps being closed when I tap the clear button?

CodePudding user response:

Give this a try...

// conform to UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
    
    // assuming this is created in Storyboard
    @IBOutlet var searchTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchTextField.addTarget(self, action: #selector(searchTextFieldDidChange(textField:)), for: .editingChanged)

        // set the delegate
        searchTextField.delegate = self
    }
    
    @objc func searchTextFieldDidChange(textField: UITextField){
        if textField.text == "" {
            textField.resignFirstResponder()
        }
        fireSearch()
    }
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        // clear the text
        //  Note: this does NOT fire searchTextFieldDidChange()
        textField.text = ""

        // resign
        textField.resignFirstResponder()

        // if you want to fire the search after text has been cleared
        //fireSearch()

        // return false to stop the default action of the clear button
        return false
    }
    func fireSearch() {
        print(#function)
    }

}
  • Related