Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
johnbakers Avatar asked Aug 08 '12 03:08

johnbakers


2 Answers

check all of your textfield call

[textfield isFirstResponder]
like image 53
adali Avatar answered Oct 26 '22 03:10

adali


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.

like image 23
Michael Dautermann Avatar answered Oct 26 '22 03:10

Michael Dautermann