29

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()
            } 
        }
    }
squaleLis
  • 6,116
  • 2
  • 22
  • 30
SwiftER
  • 1,235
  • 4
  • 17
  • 40

6 Answers6

31

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

view.endEditing(true)
Ahmed Onawale
  • 3,992
  • 1
  • 17
  • 21
  • 3
    "view.endEditing(true)" work great for touches began but it does not work for "textFieldShouldReturn" – SwiftER May 14 '16 at 16:46
31

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!

Hjalmar
  • 1,921
  • 2
  • 16
  • 19
  • 2
    Is this safe to be used, I mean, would Apple approve the app submitted to the app store with this code? – Miki Sep 23 '19 at 13:43
29

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)
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
9

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 :)

Anup Gupta
  • 1,993
  • 2
  • 25
  • 40
  • when I use this it prevents any other touch events from firing.. great at dismissing keyboards but renders by view uneditable – nbpeth Dec 31 '17 at 19:09
  • @nbpeth yes I can understand your problem this happen due to In method 3 **UIView** is the parent of all other views. – Anup Gupta Jan 01 '18 at 12:58
1

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
}
Vaisakh KP
  • 467
  • 1
  • 6
  • 25
Braham Youssef
  • 479
  • 6
  • 6
-1

Swift 4:

In case you have IBOutlets:

_ = [textFiledOne, textFiledTwo, textFiledThree].map() { $0.resignFirstResponder() }
Kasra Babaei
  • 300
  • 1
  • 3
  • 12