Skip to content

Instantly share code, notes, and snippets.

@vilanovi
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vilanovi/e52face5c6f00ce5254d to your computer and use it in GitHub Desktop.
Save vilanovi/e52face5c6f00ce5254d to your computer and use it in GitHub Desktop.
Find the first responder by swizzeling methods of UIResponder
// ************************************************************ //
// 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