事件传递机制

作者: mtry | 来源:发表于2018-02-06 20:31 被阅读22次

    主要内容

    • 理论部分
    • 常见应用

    理论部分

    iOS中事件(UIEvent)主要是以下几种,本文主要是分析触控事件(UITouch)

    1. 触控事件(UIEventTypeTouches):单点、多点触控以及各种手势操作
    2. 传感器事件(UIEventTypeMotion):重力、加速度传感器等
    3. 远程控制事件(UIEventTypeRemoteControl):远程遥控 iOS 设备多媒体播放等
    4. 按压事件(UIEventTypePresses):3D Touch(iOS 9)

    如果一个对象需要响应事件(UIEvent)那么就需要继承 UIResponder。UIView、UIViewController、UIApplication 都继承 UIResponder,所以它们都可以响应事件。

    UITouch事件传递流程

    • ...系统层面事件转换...
    • App主线程RunLoop被唤醒
    • 主线程RunLoop触发__handleEventQueue方法
    • 内部派发任务时,先通过hitTest:withEvent:找到目标视图hitTestView,封装成UITouch(对象中包含hitTestView)添加到UIEvent中的allTouches
    • 调用UIApplicationsendEvent:方法
    • 调用UIWindowsendEvent:方法
    • 目标视图hitTestView如果重载touchesBegan:, touchesEnded:, touchesMoved:, touchesCancelled: 这些方法开始响应,如果没有则会按照UIResponder响应链一直往上传递

    PS:关于hitTest:withEvent:sendEvent:的顺序可以通过hook验证

    关于hitTestView(被点击的View)

    当点击屏幕上的按钮时,是怎么定位到按钮呢?接下来我们来分析定位响应者,核心方法如下(UIView方法)

    - (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;
    - (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event; 
    

    每当手指接触屏幕,UIApplication 接收到手指的事件之后,就会去调用 UIWindow 的 hitTest:withEvent:,看看当前点击的点是不是在 window 内,如果是则继续依次调用 subView 的 hitTest:withEvent: 方法,直到找到最后需要的 view。

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
    {
        if(self.isUserInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01)
        {
            return nil;
        }
    
        if([self pointInside:point withEvent:event])
        {
            //注意优先遍历上面的视图,越晚添加越在上面
            for(UIView *subView in self.subviews.reverseObjectEnumerator)
            {
                CGPoint convertPoint = [subView convertPoint:point fromView:self];
                UIView *hitTestView = [subView hitTest:convertPoint withEvent:event];
                if(hitTestView)
                {
                    return hitTestView;
                }
            }
            return self;
        }
        return nil;
    }
    
    image_1.png

    图片来源

    关于事件响应链

    当 UIApplication 在 UIWindow 中找到 hitTestView 时,通过 sendEvent: 把事件(UIEvent)发送给UIWindow,UIWindow 也通过 sendEvent: 向 hitTestView 发送消息。这个消息是否可以响应就需要依赖 UIResponder。

    //与本文相关的主要内容
    @interface UIResponder : NSObject
    
    @property(nonatomic, readonly) UIResponder *nextResponder;
    
    @property(nonatomic, readonly) BOOL canBecomeFirstResponder; 
    @property(nonatomic, readonly) BOOL canResignFirstResponder;
    
    - (BOOL)becomeFirstResponder;
    - (BOOL)resignFirstResponder;
    
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
    - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
    - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
    - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
    - (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches NS_AVAILABLE_IOS(9_1);
    
    @end
    

    UIResponder 中的 nextResponder 是事件传递的关键。nextResponder 构成传递链有以下关系:

    • view.nextResponder == view.superView
    • controller.view.nextResponder == controller
    • controller.nextResponder == controller.view.superView 如果存在一个控制器在另一个控制器中时
    • controller.nextResponder == window
    • window.nextResponder == Appliction

    当一个 view 被 add 到 superView 上的时候,他的 nextResponder 属性就会被指向它的 superView,当 controller 被初始化的时候,controller.view 的 nextResponder 会被指向所在的 controller,而 controller 的 nextResponder 会被指向 controller.view 的 superView,这样整个 app 就通过 nextResponder 串成了一条链,也就是我们所说的响应链。

    image_2.png

    图片来源

    于是我们理解事件传递就很方便了,通过 hitTest 找到需要响应的 hitTestView,然后向其发送消息,如果 hitTestView 可以响应手势、Button 或实现了 touchesBegan、touchesEnded 等方法,那么事件找到了组织了,否则通过 nextResponder 链一直找下去。

    常见应用

    理解了事件传递机制,我们可以灵活的运用寻找 hitTestView 和事件传递。

    1、 扩大响应范围

    我们经常遇到这样的情形,就是我们希望扩大按钮的点击区域。这时我们可以通过 hitTest 来进行控制。

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
    {
        if(self.isUserInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01)
        {
            return nil;
        }
    
        //上下左右扩大20px
        CGRect newRect = CGRectInset(self.bounds, -20, -20);
        if(CGRectContainsPoint(newRect, point))
        {
            for(UIView *subView in self.subviews.reverseObjectEnumerator)
            {
                CGPoint convertPoint = [subView convertPoint:point fromView:self];
                UIView *hitTestView = [subView hitTest:convertPoint withEvent:event];
                if(hitTestView)
                {
                    return hitTestView;
                }
            }
            return self;
        }
        return nil;
    }
    

    2、事件转发

    有时我们需要实现,弹个窗显示一些内容,内容外部需要一个半透明的挡板,当点击挡板时,关闭弹窗。我之前会为挡板添加一个手势来关闭,如果了解了事件转发机制,我们只需要重载一下 touchesBegan: withEvent: 即可。

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event
    {
        [self close];
    }
    

    参考资料

    1. 深入浅出iOS事件机制
    2. iOS事件分发机制(一) hit-Testing
    3. iOS事件分发机制(二)The Responder Chain
    4. 事件传递响应链
    5. iOS触摸事件的流动

    相关文章

      网友评论

        本文标题:事件传递机制

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