Last active
August 29, 2015 14:05
-
-
Save AfonsoTsukamoto/5b05f116b966c49a7997 to your computer and use it in GitHub Desktop.
A category to get a touches began delegate from UIWIndow
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
static const void *touchesDelegateKey = &touchesDelegateKey; | |
static void (*Original_touchesBeganMethod)(id, SEL, NSSet *, UIEvent *); | |
static void SwizzledTouchesBegan(id _self, SEL _cmd, NSSet *touches, UIEvent *event){ | |
if([_self touchesDelegate] != nil){ | |
if([[_self touchesDelegate] respondsToSelector:@selector(windowTouches:withEvent:)]){ | |
[[_self touchesDelegate] windowTouches:touches withEvent:event]; | |
} | |
} | |
return Original_touchesBeganMethod(_self, _cmd, touches, event); | |
} | |
@implementation UIWindow (Touches) | |
-(void)setTouchesDelegate:(id<UIWindowTouchesProtocol>)touchesDelegate | |
{ | |
objc_setAssociatedObject(self, touchesDelegateKey, touchesDelegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); | |
} | |
-(id<UIWindowTouchesProtocol>)touchesDelegate | |
{ | |
return objc_getAssociatedObject(self, touchesDelegateKey); | |
} | |
+ (void)load { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
Class class = [UIWindow class]; | |
SEL originalSelector = @selector(touchesBegan:withEvent:); | |
IMP replacement = (IMP)SwizzledTouchesBegan; | |
IMP *store = (IMP*)&Original_touchesBeganMethod; | |
IMP originalImp = NULL; | |
Method method = class_getInstanceMethod(class, originalSelector); | |
if (method) { | |
const char *type = method_getTypeEncoding(method); | |
originalImp = class_replaceMethod(class, originalSelector, replacement, type); | |
if (!originalImp) { | |
originalImp = method_getImplementation(method); | |
} | |
} | |
if (originalImp && store) { *store = originalImp; } | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment