6

If you have several text fields on the screen, and the keyboard pops up for each one when they are tapped, what if you want to programmatically hide the keyboard, or resign first responder, but you don't know which textfield to send the resignFirstResponder message to? Is there a way to identify which object/textField should get this message?

johnbakers
  • 24,158
  • 24
  • 130
  • 258
  • possible duplicate of [Get the current first responder without using a private API](http://stackoverflow.com/questions/1823317/get-the-current-first-responder-without-using-a-private-api) – jscs Aug 08 '12 at 04:27
  • I think `[self.view endEditing:YES];` is better solution for this. – Mihir Oza Apr 20 '17 at 14:15

5 Answers5

8

check all of your textfield call

[textfield isFirstResponder]
adali
  • 5,977
  • 2
  • 33
  • 40
3

You could keep track of which text field is the first responder by either setting your view controller to be the delegate object of all text fields and then when your subclassed text fields gets the "becomeFirstResponder" method call, tell your view controller which text field is the current one.

Or, there's a more blunt force approach which is a category extension to "UIView":

@implementation UIView (FindAndResignFirstResponder)
- (BOOL)findAndResignFirstResponder
{
    if (self.isFirstResponder) {
        [self resignFirstResponder];
        return YES;     
    }
    for (UIView *subView in self.subviews) {
        if ([subView findAndResignFirstResponder])
            return YES;
    }
    return NO;
}
@end

which I got from this potentially very related question.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
1

You Can Check Your all TextField and than Identify Easily.

[textfield isFirstResponder];
Raju
  • 759
  • 3
  • 18
0

There is no public method to get the current first responder, but you can do things to still get it; The first one is obviously to keep track of this yourself. You can do this in various way and if you don't want to touch any existing class but just want it to work, a category and method swizzling will do the trick. The more cleaner solution however is to iterate through the view hierarchy and ask the views wether they are the current first responder. You can start with the root UIWindow and start iterating, or you can start with your current UIViewController's view, but keep in mind that the current first responder doesn't have to be part of your roots UIWindow view hierarchy (eg. if you have a text field inside an UIAlertView).

JustSid
  • 25,168
  • 7
  • 79
  • 97
-1

Try this (Swift 3):

if textField.isEditing {
   textField.resingFirstResponder()
}
Axel
  • 3,331
  • 11
  • 35
  • 58