Last active
August 29, 2015 14:01
-
-
Save vilanovi/e52face5c6f00ce5254d to your computer and use it in GitHub Desktop.
Find the first responder by swizzeling methods of UIResponder
This file contains hidden or 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 "NSObject+Swizzle.h" // <-- https://gist.github.com/vilanovi/688564548c904fd7b2d2 | |
static NSHashTable *__instances = nil; | |
@implementation UIResponder (FirstResponder) | |
+ (UIResponder*)firstResponder | |
{ | |
id firstResponder = nil; | |
NSHashTable *table = [__instances copy]; | |
for (UIResponder *responder in table) | |
{ | |
if ([responder isFirstResponder]) | |
{ | |
firstResponder = responder; | |
break; | |
} | |
} | |
return firstResponder; | |
} | |
+ (void)load | |
{ | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
__instances = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory]; | |
[self swizzleSelector:@selector(init) withSelector:@selector(init_custom)]; | |
}); | |
} | |
- (id)init_custom | |
{ | |
self = [self init_custom]; | |
if (self) | |
{ | |
[__instances addObject:self]; | |
} | |
return self; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment