Snippet: Finding the Current First Responder

In iOS there is no simple call to retrieve the current first responder (without resorting to private APIs). A google search turns up lots of methods that involving walking the view hierarchy, but I really like this simple, efficient method by Jakob Egger posted as an answer to this question on stack overflow.

#import "UIResponder+FirstResponder.h"

static __weak id currentFirstResponder;

@implementation UIResponder (FirstResponder)

+(id)currentFirstResponder {
    currentFirstResponder = nil;
    [[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) to:nil from:nil forEvent:nil];
    return currentFirstResponder;
}

-(void)findFirstResponder:(id)sender {
   currentFirstResponder = self;
}

@end

I don’t normally repost code from stack overflow, but the google incantations necessary to find this are non-obvious.


About idz

A professional software engineer dabbling in iOS app development.
This entry was posted in Code Snippets. Bookmark the permalink.

Leave a Reply