美文网首页
iOS 获取整个app在屏幕上的点击坐标

iOS 获取整个app在屏幕上的点击坐标

作者: MccReeee | 来源:发表于2017-10-19 17:32 被阅读1014次

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

#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]));
    }
}

相关文章

网友评论

      本文标题:iOS 获取整个app在屏幕上的点击坐标

      本文链接:https://www.haomeiwen.com/subject/kjhpuxtx.html