项目中有个需求是想拿到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

  1. #import <UIKit/UIKit.h>
  2. #import “AppDelegate.h”
  3. #import “MRApplication.h”
  4. int main(int argc, char * argv[]) {
  5. @autoreleasepool {
  6. return UIApplicationMain(argc, argv, NSStringFromClass([MRApplication class]), NSStringFromClass([AppDelegate class]));
  7. }
  8. }