简体   繁体   中英

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?

检查所有文本字段调用

[textfield isFirstResponder]

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 .

您可以检查所有TextField而不是轻松识别。

[textfield isFirstResponder];

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

Try this (Swift 3):

if textField.isEditing {
   textField.resingFirstResponder()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM