iOS 获取整个app在屏幕上的点击坐标和点击事件
项目中有个需求是想拿到app里所有在屏幕上的点击坐标
解决方案创建一个子类继承自UIApplication
,然后在sendEvent
方法中获取并判断
#import “MRApplication.h”
#include <CommonCrypto/CommonCrypto.h>
@interface MRApplication()
@property(nonatomic,assign) BOOL isMoved;
@end
@implementation MRApplication
– (void)sendEvent:(UIEvent *)event{
if (event.type==UIEventTypeTouches) {
UITouch *touch = [event.allTouches anyObject];
if (touch.phase == UITouchPhaseBegan) {
self.isMoved = NO;
}
if (touch.phase == UITouchPhaseMoved) {
self.isMoved = YES;
}
if (touch.phase == UITouchPhaseEnded) {
if (!self.isMoved && event.allTouches.count == 1) {
UITouch *touch = [event.allTouches anyObject];
CGPoint locationPointWindow = [touch preciseLocationInView:touch.window];
NSLog(@”TouchLocationWindow:(%.1f,%.1f)”,locationPointWindow.x,locationPointWindow.y);
}
self.isMoved = NO;
}
}
[super sendEvent:event];
}
@end
其实在touch
对象中已经有了View的信息,如果想获取在view中的相对坐标也可以.使用touch.view
即可
CGPoint locationPointWindow = [touch preciseLocationInView:touch.view];
注意:这个MRApplication需要在main.m
中引入,然后就可以拦截整个app所有的点击事件了,其中我对滑动和多点触控做了处理,不加if
判断是会拿到滑动和多点触控时的UIEvent
的
-
-
-
-
-
int main(int argc, char * argv[]) {
-
@autoreleasepool {
-
return UIApplicationMain(argc, argv, NSStringFromClass([MRApplication class]), NSStringFromClass([AppDelegate class]));
-
}
-
}