Search code examples
swiftuitextfielddelegate

Swift how to resign first responder on all uiTextfield


I would like to use resign the first responder on all uitextfield. I'm able to complete this by placing the uitextfields in an array but I wanted to avoid using the array. the resign should happen to all type of uiTextField how can this be done.

This works fine

    class ViewController: UIViewController, UITextFieldDelegate {
        @IBOutlet weak var text: UITextField!
        @IBOutlet weak var textFieldtwo: UITextField!

        var textField = [UITextField]()

        override func viewDidLoad() {
            super.viewDidLoad()
            self.textField = [text,textFieldtwo]

            for item in textField {
                item.delegate = self
            }
        }

        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            print("text")

            for item in textField {
                item.resignFirstResponder()
            } 
        }
    }

Solution

  • You can try this:

    for textField in self.view.subviews where textField is UITextField {
        textField.resignFirstResponder()
    }
    

    But if you just want to dismiss the Keyboard by pressing the return on the keyboard or tapping anywhere on the screen without using touchesBegan

    You can try with this:

    // For pressing return on the keyboard to dismiss keyboard
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        for textField in self.view.subviews where textField is UITextField {
            textField.resignFirstResponder()
        }
        return true
    }
    

    ...

    func hideKeyboard() {
        view.endEditing(true)
    }
    

    And add this to your viewDidLoad:

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
    view.addGestureRecognizer(tapGesture)