johnbakers
johnbakers

Reputation: 24750

How to identify which textfield is currently first responder

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?

Upvotes: 6

Views: 8510

Answers (5)

Renato Machado Filho
Renato Machado Filho

Reputation: 31

Try this (Swift 3):

if textField.isEditing {
   textField.resingFirstResponder()
}

Upvotes: -1

Raju
Raju

Reputation: 759

You Can Check Your all TextField and than Identify Easily.

[textfield isFirstResponder];

Upvotes: 1

Michael Dautermann
Michael Dautermann

Reputation: 89509

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.

Upvotes: 3

adali
adali

Reputation: 5977

check all of your textfield call

[textfield isFirstResponder]

Upvotes: 8

JustSid
JustSid

Reputation: 25318

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

Upvotes: 0

Related Questions