首页 > 代码库 > 源码0306-hitText底层实现

源码0306-hitText底层实现

 

//  XMGWindow.m//  04-事件的产生和传递#import "XMGWindow.h"@implementation XMGWindow// 事件传递的时候调用// 什么时候调用:当事件传递给控件的时候,就会调用控件的这个方法,去寻找最合适的view// 作用:寻找最合适的view// point:当前的触摸点,point这个点的坐标系就是方法调用者//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event//{//    // 调用系统的做法去寻找最合适的view,返回最合适的view//    UIView *fitView = [super hitTest:point withEvent:event];//    ////    NSLog(@"fitView--%@",fitView);//    //    //    return fitView;//}// 作用:判断当前这个点在不在方法调用者(控件)上//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event//{//    return YES;//}//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event//{////    NSLog(@"%s",__func__);//}// 点击黄色视图 -》 事件 -》 UIApplication -> UIWindow// 因为所有的视图类都是继承BaseView- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{        // 1.判断当前控件能否接收事件    if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) return nil;        // 2. 判断点在不在当前控件    if ([self pointInside:point withEvent:event] == NO) return nil;        // 3.从后往前遍历自己的子控件    NSInteger count = self.subviews.count;        for (NSInteger i = count - 1; i >= 0; i--) {        UIView *childView = self.subviews[i];                // 把当前控件上的坐标系转换成子控件上的坐标系        CGPoint childP = [self convertPoint:point toView:childView];                UIView *fitView = [childView hitTest:childP withEvent:event];                        if (fitView) { // 寻找到最合适的view            return fitView;        }    }    // 循环结束,表示没有比自己更合适的view    return self;}@end

 

//  BaseView.m//  04-事件的产生和传递#import "BaseView.h"@implementation BaseView- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    NSLog(@"%@---touchesBegan",[self class]);}// UIApplication -> [UIWindow hitTest:withEvent:] -> whiteView hitTest:withEvent// 因为所有的视图类都是继承BaseView- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{//    NSLog(@"%@--hitTest",[self class]);//    return [super hitTest:point withEvent:event];            // 1.判断当前控件能否接收事件    if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) return nil;        // 2. 判断点在不在当前控件    if ([self pointInside:point withEvent:event] == NO) return nil;        // 3.从后往前遍历自己的子控件    NSInteger count = self.subviews.count;        for (NSInteger i = count - 1; i >= 0; i--) {        UIView *childView = self.subviews[i];                // 把当前控件上的坐标系转换成子控件上的坐标系     CGPoint childP = [self convertPoint:point toView:childView];               UIView *fitView = [childView hitTest:childP withEvent:event];                        if (fitView) { // 寻找到最合适的view            return fitView;        }                    }        // 循环结束,表示没有比自己更合适的view    return self;    }@end

 

源码0306-hitText底层实现