3

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.

5 Answers 5

25

[...] 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 
Sign up to request clarification or add additional context in comments.

2 Comments

Why does it return UIView and not UITextField?
@yourfriendzak Because UITextField is not the only type of object that can become the first responder.
4

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

Comments

3
if(![myTextField isFirstResponder]) { // do stuff } 

Comments

1

I might do like this

Add property to ViewController

@property (nonatomic, strong) UITextField *firstRespondField; 

Register TextField Notificaiton

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidEndEdition:) name:UITextFieldTextDidEndEditingNotification object:nil]; 

Dont forget remove it on Dealloc

[[NSNotificationCenter defaultCenter] removeObserver:self]; 

Then Implement 2 method

 - (void)textFieldTextDidBeginEditing:(NSNotification *)aNotification { self.firstRespondField = aNotification.object; } - (void)textFieldTextDidEndEdition:(NSNotification *)aNotification { self.firstRespondField = nil; } 

Finally, I might get FirstResponder object by

self.firstRespondField 

Comments

0

You can just call UIView.IsFirstResponder on the view you want to know if it's the first responder.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.