項(xiàng)目中有個(gè)需求是想拿到app里所有在屏幕上的點(diǎn)擊坐標(biāo)
解決方案創(chuàng)建一個(gè)子類繼承自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
其實(shí)在touch對(duì)象中已經(jīng)有了View的信息,如果想獲取在view中的相對(duì)坐標(biāo)也可以.使用touch.view即可
CGPoint locationPointWindow = [touch preciseLocationInView:touch.view];
注意:這個(gè)MRApplication需要在main.m中引入,然后就可以攔截整個(gè)app所有的點(diǎn)擊事件了,其中我對(duì)滑動(dòng)和多點(diǎn)觸控做了處理,不加if判斷是會(huì)拿到滑動(dòng)和多點(diǎn)觸控時(shí)的UIEvent的
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "MRApplication.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, NSStringFromClass([MRApplication class]), NSStringFromClass([AppDelegate class]));
}
}