Swift how to resign first responder on all uiTextfield

SwiftER picture SwiftER · May 14, 2016 · Viewed 34.3k times · Source

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()
            } 
        }
    }

Answer

Hjalmar picture Hjalmar · Dec 2, 2016

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!