10

I have seen this question, but the question is how to know which textView is the first responder? This question looked promising to figure out the first responder, but it turns out that it calls private APIs. Is there any way to hide the keyboard or to figure out the first responder as the-one-who-has-the-keyboard?

Community
  • 1
  • 1
Dan Rosenstark
  • 64,546
  • 54
  • 267
  • 405
  • possible duplicate of [Easy way to dismiss keyboard?](http://stackoverflow.com/questions/741185/easy-way-to-dismiss-keyboard) – Senseful Aug 19 '14 at 16:53
  • Also see [Dismiss keyboard on touch anywhere outside of textfield](http://stackoverflow.com/questions/11274119/dismiss-keyboard-on-touch-anywhere-outside-uitextfield) – ToolmakerSteve Mar 14 '17 at 05:21

3 Answers3

26

It's easy:

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

take a look at UIView Class Reference.

Andrey Zverev
  • 4,371
  • 1
  • 26
  • 34
  • 1
    I'll have to verify this before marking it as accepted. On the other hand, if you linked to some docs, that would be better for me and SO. – Dan Rosenstark Nov 10 '11 at 03:50
  • UIWindow is a subclass of UIView; it inherits `endEditing` method from UIView. – Andrey Zverev Nov 18 '11 at 13:01
  • Worked perfectly for me - my use case was i have 4 different tableViews on a UIView that have their hidden property turned on and off by a UISegmentedController making just one appear at a time. - i needed to get the keyboard to go away if someone changed to a different table view. – SimonTheDiver Jun 13 '13 at 11:02
4

[textView isFirstResponder] should tell you if it's the first responder. I guess you could just loop through all text fields in your class to check if it's the first responder.

Or you could just call resignFirstResponder on every textField, and it'll still work.

Tejaswi Yerukalapudi
  • 8,629
  • 12
  • 57
  • 101
  • Actually on second thought, the second part of your answer makes me realize that thanks to my well-designed app :), I can just do that. – Dan Rosenstark Jul 01 '10 at 20:12
3

I believe you should pick something to become the first responder, something which probably doesn't do anything on its own, and call -[UIResponder becomeFirstResponder] on it. This would work well with a UIViewController or UIWindow (which you can get through -[UIView window], I think) because these would have the most similar responder chains, and would make the current firstResponder loose its firstResponder status, dismissing the keyboard, but also wouldn't bring up the keyboard, as it would not be a UITextField.

Jared Pochtar
  • 4,727
  • 2
  • 23
  • 38