Skip to content

Instantly share code, notes, and snippets.

@vilanovi
Last active August 29, 2015 14:01
Show Gist options
  • Save vilanovi/1f5670064c710bb2be12 to your computer and use it in GitHub Desktop.
Save vilanovi/1f5670064c710bb2be12 to your computer and use it in GitHub Desktop.
Recursive way to find the first responder
// ************************************************************ //
// UIResponder+FirstResponder.h
// ************************************************************ //
@interface UIResponder (FirstResponder)
+ (UIResponder*)firstResponder;
@end
// ************************************************************ //
// UIResponder+FirstResponder.m
// ************************************************************ //
#import "UIResponder+FirstResponder.h"
@interface UIView (FindFirstResponder)
- (UIView*)findFirstResponder;
@end
@interface UIViewController (FindFirstResponder)
- (id)findFirstResponder;
@end
@implementation UIView (FindFirstResponder)
- (UIView *)findFirstResponder
{
if (self.isFirstResponder)
return self;
for (UIView *subView in self.subviews)
{
UIView *firstResponder = [subView findFirstResponder];
if (firstResponder != nil)
return firstResponder;
}
return nil;
}
@end
@implementation UIViewController (FindFirstResponder)
- (id)findFirstResponder
{
if (self.isFirstResponder)
return self;
id firstResponder = [self.view findFirstResponder];
if (firstResponder != nil)
return firstResponder;
for (UIViewController *childViewController in self.childViewControllers)
{
firstResponder = [childViewController findFirstResponder];
if (firstResponder != nil)
return firstResponder;
}
return nil;
}
@end
@implementation UIResponder (FirstResponder)
+ (UIResponder*)firstResponder
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow *window in [windows copy])
{
if ([window isFirstResponder])
return window;
id firstResponder = [window.rootViewController findFirstResponder];
if (firstResponder)
return firstResponder;
}
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment