Get firstresponder in Objective C

I am having trouble trying to figure out which UITextField is the current First Responder.

What I am trying to do is a set a boolean value if the user clicks in a particular UITextField . So to do that I need to be able to tell if this particular text field has become the first responder.

I know how to set the first responder but just not sure how to tell if a field has actually become the first responder.


[...] but just not sure how to tell if a field has actually become the first responder.

UIView inherits the isFirstResponder method from UIResponder which tells you this.

The easiest way to find whatever the first responder is without checking individual controls/views and without multiple methods for all of the different types of possible first responders is to just make a category on UIView which adds a findFirstResponder method:

UIView+FirstResponder.h

#import <UIKit/UIKit.h>

@interface UIView (FirstResponder)
- (UIView *)findFirstResponder;
@end

UIView+FirstResponder.m

#import "UIView+FirstResponder.h"

@implementation UIView (FirstResponder)

- (UIView *)findFirstResponder
{
    if ([self isFirstResponder])
        return self;

    for (UIView * subView in self.subviews) 
    {
        UIView * fr = [subView findFirstResponder];
        if (fr != nil)
            return fr;
    }

    return nil;
}

@end

Why not using the UITextFieldDelegate and implement the textFieldDidBeginEditing: method? This will be called as soon as the textfield gains the focus.

UITextFieldDelegate Protocol Reference


if(![myTextField isFirstResponder])
{
    // do stuff
}
链接地址: http://www.djcxy.com/p/44286.html

上一篇: 键盘没有被解雇

下一篇: 在Objective C中获得第一响应者