我的目标是在任何视图上检测我的应用程序内的任何触摸事件......(即在我的应用程序内,任何地方的任何触摸事件都应该被检测到......)我已经通过使用 UIApplication 子类化我的 appDelegate 类来尝试它,但它给了我错误
如何解决该错误或以任何其他方式实现它...
请帮忙
谢谢
我的目标是在任何视图上检测我的应用程序内的任何触摸事件......(即在我的应用程序内,任何地方的任何触摸事件都应该被检测到......)我已经通过使用 UIApplication 子类化我的 appDelegate 类来尝试它,但它给了我错误
如何解决该错误或以任何其他方式实现它...
请帮忙
谢谢
好的,我已经回答了那个链接的问题。但是,您可能需要考虑一种不同的方法,即使用您自己的实现class_replaceMethod()
“混合”触摸方法。UIView
这是一个在 IOS 4 和 5 上测试正常的检测器。有一个警告。如果您使用手势识别器,则必须在它们进入 UIGestureRecognizerStateEnded 状态时将全局 AppTouched 设置为 false。
#import <objc/runtime.h>
Boolean AppTouched = false; // provide a global for touch detection
static IMP iosBeginTouch = nil; // avoid lookup every time through
static IMP iosEndedTouch = nil;
static IMP iosCanedTouch = nil;
// implement detectors for UIView
@implementation UIView (touchesBeganDetector)
- (void)touchesBeganDetector:(NSSet *)touches withEvent:(UIEvent *)event
{
AppTouched = true;
if ( iosBeginTouch == nil )
iosBeginTouch = [self methodForSelector:
@selector(touchesBeganDetector:withEvent:)];
iosBeginTouch( self, @selector(touchesBegan:withEvent:), touches, event );
}
@end
@implementation UIView (touchesEndedDetector)
- (void)touchesEndedDetector:(NSSet *)touches withEvent:(UIEvent *)event
{
AppTouched = false;
if ( iosEndedTouch == nil )
iosEndedTouch = [self methodForSelector:
@selector(touchesEndedDetector:withEvent:)];
iosEndedTouch( self, @selector(touchesEnded:withEvent:), touches, event );
}
@end
@implementation UIView (touchesCancledDetector)
- (void)touchesCancledDetector:(NSSet *)touches withEvent:(UIEvent *)event
{
AppTouched = false;
if ( iosCanedTouch == nil )
iosCanedTouch = [self methodForSelector:
@selector(touchesCancledDetector:withEvent:)];
iosCanedTouch( self, @selector(touchesCancelled:withEvent:), touches, event );
}
@end
// http://stackoverflow.com/questions/1637604/method-swizzle-on-iphone-device
static void Swizzle(Class c, SEL orig, SEL repl )
{
Method origMethod = class_getInstanceMethod(c, orig );
Method newMethod = class_getInstanceMethod(c, repl );
if(class_addMethod( c, orig, method_getImplementation(newMethod),
method_getTypeEncoding(newMethod)) )
class_replaceMethod( c, repl, method_getImplementation(origMethod),
method_getTypeEncoding(origMethod) );
else
method_exchangeImplementations( origMethod, newMethod );
}
@interface touchDetector : NSObject {}
- (id) init;
@end
@implementation touchDetector
- (id) init
{
if ( ! [ super init ] )
return nil;
SEL rep = @selector( touchesBeganDetector:withEvent: );
SEL orig = @selector( touchesBegan:withEvent: );
Swizzle( [UIView class], orig, rep );
rep = @selector( touchesEndedDetector:withEvent: );
orig = @selector( touchesEnded:withEvent: );
Swizzle( [UIView class], orig, rep );
rep = @selector( touchesCancledDetector:withEvent: );
orig = @selector( touchesCancelled:withEvent: );
Swizzle( [UIView class], orig, rep );
return self;
}
@end