peter peter - 6 months ago 120
Swift Question

Swift how to resign first responder on all uiTexfield

I would like to use resign first responder on all uitextfield. im 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 work 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()
}

}
}

Answer

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)