Last active
August 29, 2015 14:01
-
-
Save vilanovi/1f5670064c710bb2be12 to your computer and use it in GitHub Desktop.
Recursive way to find the first responder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ************************************************************ // | |
// 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