Swift how to resign first responder on all uiTextfield

38,422

Solution 1

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)

Solution 2

Or just use a more global approach. (Swift 3.0)

UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil);

This will dismiss any active field as it resigns the current first responder. Good luck coding!

Solution 3

A simpler approach would by to end editing on the UIView containing the UITextFields by saying:

view.endEditing(true)

Solution 4

Now In Swift 3, the easiest methods are

Method 1: called when 'return' key pressed.

func textFieldShouldReturn(_ textField: UITextField) -> Bool 
 {
 textField1.resignFirstResponder()
 textField2.resignFirstResponder()
        return true;
    }

Method 2: called when 'return' key pressed.

func textFieldShouldReturn(_ textField: UITextField) -> Bool 
    {
    self.view.endEditing(true)
        return true;
    }

Method 3: Global Method Write in view did load

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))

Note: Don't forget to add this. Other wise its not work.

UIGestureRecognizerDelegate, UITextFieldDelegate

I hope it will work for you :)

Solution 5

resignFirstResponder with toolbars buttons Swift4 ##

You can try this : 1. check the Textfield Delegate
class CoursesViewController: UIViewController,UITextFieldDelegate {

  1. create a TextField var: var currentTextField:UITextField!

  2. create "done" & "cancel" buttons toolBar in your TextField

    func addDoneCancel(_ textField : UITextField) {
    
        curentTextField = textField
    
        // ToolBar
        let toolBar = UIToolbar()
        toolBar.barStyle = .default
        toolBar.isTranslucent = true
        toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
        toolBar.sizeToFit()
    
        // Adding Button ToolBar
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(CoursesViewController.doneClick))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(CoursesViewController.cancelClick))
        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true
        textField.inputAccessoryView = toolBar
    }
    

4.actions of toolbar buttons

@objc func doneClick(){
    curentTextField.resignFirstResponder()
}

@objc func cancelClick(){
    curentTextField.resignFirstResponder()
}

5.UItextField delegate

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    curentTextField = textField
    addDoneCancel(textField)
    return true
}

func textFieldDidBeginEditing(_ textField: UITextField) {    
    //delegate method
}

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {  
    //delegate method
    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   
    //delegate method
    textField.resignFirstResponder()

    return true
}
Share:
38,422

Related videos on Youtube

SwiftER
Author by

SwiftER

Im Business owner and developer. I believe that everyone in the world should learn to code. By learning coding everyone will understand ways to solve problems in the world.

Updated on February 27, 2020

Comments

  • SwiftER
    SwiftER over 3 years

    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()
                } 
            }
        }
    
  • SwiftER
    SwiftER over 7 years
    "view.endEditing(true)" work great for touches began but it does not work for "textFieldShouldReturn"
  • Essam Fahmi
    Essam Fahmi about 6 years
    please, what is purpose from resignFirstResponder() ?
  • Khuong
    Khuong about 6 years
  • nbpeth
    nbpeth almost 6 years
    when I use this it prevents any other touch events from firing.. great at dismissing keyboards but renders by view uneditable
  • Anup Gupta
    Anup Gupta almost 6 years
    @nbpeth yes I can understand your problem this happen due to In method 3 UIView is the parent of all other views.
  • Miki
    Miki about 4 years
    Is this safe to be used, I mean, would Apple approve the app submitted to the app store with this code?