当前位置: 移动技术网 > IT编程>移动开发>IOS > 事件传递和响应链

事件传递和响应链

2019年06月12日  | 移动技术网IT编程  | 我要评论

五星级性技,意念杀庄,善行日记

前言

看关于这方面的文章基本没有能涉及到uigesturerecognizers相关的文章,因此决定写这样一篇文章。也是我的第一篇文章,如有什么不对请及时指正。
本文主要通过一些实际测试来便于大家理解。

正文

事件传递和响应链流程图

  • iokit.framework 为系统内核的库
  • springboard.app 相当于手机的桌面
  • source1 主要接收系统的消息
  • source0 - uiapplication - uiwindow
  • 从window开始系统会调用hittest:withevent:pointinside来找到最优响应者,具体过程可参考下图
    hittest
    • 比如我们在self.view 上依次添加view1、view2、view3(3个view是同级关系),那么系统用hittest以及pointinside时会先从view3开始便利,如果pointinside返回yes就继续遍历view3的subviews(如果view3没有子视图,那么会返回view3),如果pointinside返回no就开始遍历view2。反序遍历,最后一个添加的subview开始。也算是一种算法优化。后面会具体介绍hittest的内部实现和具体使用场景。
  • uitouch会给gesturerecognizers和最优响应者也就是hittestview发送消息
    • 默认view会走其touchbegan:withevent:等方法,当gesturerecognizers找到识别的gesturerecognizer后,将会独自占有该touch,即会调用其他gesturerecognizer和hittest view的touchcancelled:withevent:方法,并且它们不再收到该touche事件,也就不会走响应链流程。下面会具体阐述uicontol和uiscrollview和其子类与手势之间的冲突和关系。
  • 当该事件响应完毕,主线程的runloop开始睡眠,等待下一个事件。

1.hittest:withevent:和pointinside

1.1 hittest:withevent:和pointinside 演练

  • 测试hittest和pointinside执行过程

    gsgrayview *grayview = [[gsgrayview alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth/2, 400)];
    [self.view addsubview:grayview];
    
    gsredview *redview = [[gsredview alloc] initwithframe:cgrectmake(0, 0, grayview.bounds.size.width / 2, grayview.bounds.size.height / 3)];
    [grayview addsubview:redview];
    
    gsblueview *blueview = [[gsblueview alloc] initwithframe:cgrectmake(grayview.bounds.size.width/2, grayview.bounds.size.height * 2/3, grayview.bounds.size.width/2, grayview.bounds.size.height/3)];
    
    // blueview.userinteractionenabled = no;
    // blueview.hidden = yes;
    // blueview.alpha = 0.1;//0.0;
    [grayview addsubview:blueview];
    
    gsyellowview *yellowview = [[gsyellowview alloc] initwithframe:cgrectmake(cgrectgetminx(grayview.frame), cgrectgetmaxy(grayview.frame) + 20, grayview.bounds.size.width, 100)];
    [self.view addsubview:yellowview];

    hittest测试

    点击redview:
    yellowview -> grayview -> blueview -> redview
  • 当点击redview时,因为yellowview和grayview同级,yellowview比grayview后添加,所以先打印yellowview,由于触摸点不在yellowview中因此打印grayview,然后遍历grayview的subviews分别打印blueview和redview。
  • 当hittest返回nil时,也不会打印pointinside。因此可以得出pointinside是在hittest后面执行的。
  • 当view的userinteractionenabled为no、hidden为yes或alpha<=0.1时,也不会打印pointinside方法。因此可以推断出在hittest方法内部会判断如果这些条件一个成立则会返回nil,也不会调用pointinside方法。
  • 如果在grayview的hittest返回[super hittest:point event:event],则会执行gery.subviews的遍历(subviews 的 hittest 与 pointinside),grayview的pointinside是判断触摸点是否在grayview的bounds内,grayview的hittest是判断是否需要遍历他的subviews.
  • pointinside只是在执行hittest时,会在hittest内部调用的一个方法。也就是说pointinside是hittest的辅助方法。
  • hittest是一个递归函数

    1.2 hittest:withevent:内部实现代码还原

- (uiview *)hittest:(cgpoint)point withevent:(uievent *)event {
    nslog(@"-----%@",self.nextresponder.class);
    if (!self.isuserinteractionenabled || self.ishidden || self.alpha <= 0.01) return nil;
    //判断点在不在这个视图里
    if ([self pointinside:point withevent:event]) {
        //在这个视图 遍历该视图的子视图
        for (uiview *subview in [self.subviews reverseobjectenumerator]) {
            //转换坐标到子视图
            cgpoint convertedpoint = [subview convertpoint:point fromview:self];
            //递归调用hittest:withevent继续判断
            uiview *hittestview = [subview hittest:convertedpoint withevent:event];
            if (hittestview) {
                //在这里打印self.class可以看到递归返回的顺序。
                return hittestview;
            }
        }
        //这里就是该视图没有子视图了 点在该视图中,所以直接返回本身,上面的hittestview就是这个。
        nslog(@"命中的view:%@",self.class);
        return self;
    }
    //不在这个视图直接返回nil
    return nil;
}

1.3 pointinside运用:增大热区范围

  • 在开发过程中难免会遇到需要增大uibutton等的热区范围,假如uibutton的布局不允许修改,那么就需要用到pointinside来增大uibutton的点击热区范围。具体实现代码如下:
- (bool)pointinside:(cgpoint)point withevent:(uievent *)event {
    
    nslog(@"%@ -- pointinside",self.class);
    cgrect bounds = self.bounds;
    //若原热区小于200x200,则放大热区,否则保持原大小不变
    //一般热区范围为40x40 ,此处200是为了便于检测
    cgfloat widthdelta = max(200 - bounds.size.width, 0);
    cgfloat heightdelta = max(200 - bounds.size.height, 0);
    bounds = cgrectinset(bounds, -0.5 * widthdelta, -0.5 * heightdelta);
    return cgrectcontainspoint(bounds, point);
    
}
  • 也就是说如果button的size小于200*200,则点击button相对中心位置上下左右各100的范围内即使超出button,也可以响应点击事件

2.响应链

2.1 响应链的组成

respondchain

还用上面那个栗子:
点击redview:
redview -> grayview -> viewcontroller -> ...

因为只实现到controller的touches事件方法因此只打印到controller。

  • 响应链是通过nextresponder属性组成的一个链表。
    • 点击的view有 superview,nextresponder就是superview;
    • view.nextresponder.nextresponder是viewcontroller 或者是 view.superview. view
    • view.nextresponder.nextresponder.nextresponder是 uiwindow (非严谨,便于理解)
    • view.nextresponder.nextresponder.nextresponder. nextresponder是uiapplication、uiappdelate、直到nil (非严谨,便于理解)
  • touch事件就是根据响应链的关系来层层调用(我们重写touch 要记得 super 调用,不然响应链会中断)。
  • 比如我们监听self.view的touch事件,也是因为subviews的touch都在同一个响应链里。

2.2 uicontrol阻断响应链

把上面栗子中的grayview替换成一个button:

    gsexpandbutton *expandbutton = [[gsexpandbutton alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth/2, 400)];
    expandbutton.backgroundcolor = [uicolor lightgraycolor];
    [expandbutton settitle:@"点我啊" forstate:uicontrolstatenormal];
    [expandbutton addtarget:self action:@selector(expandbuttonclick:) forcontrolevents:uicontroleventtouchdown];
    [self.view addsubview:expandbutton];
    
    self.redview = [[gsredview alloc] initwithframe:cgrectmake(0, 0, expandbutton.bounds.size.width / 2, expandbutton.bounds.size.height / 3)];
    [expandbutton addsubview:self.redview];
    
    self.blueview = [[gsblueview alloc] initwithframe:cgrectmake(expandbutton.bounds.size.width/2, expandbutton.bounds.size.height * 2/3, expandbutton.bounds.size.width/2, expandbutton.bounds.size.height/3)];
    
    //    blueview.userinteractionenabled = no;
    //    blueview.hidden = yes;
    //    blueview.alpha = 0.1;//0.0;
    [expandbutton addsubview:self.blueview];
    
    self.yellowview = [[gsyellowview alloc] initwithframe:cgrectmake(cgrectgetminx(expandbutton.frame), cgrectgetmaxy(expandbutton.frame) + 20, expandbutton.bounds.size.width, 100)];
    [self.view addsubview:self.yellowview];

点击redview:
redview -> expandbutton

  • 虽然点击redview,虽然button的touches事件方法也走了但是依然不会响应button的target的action方法,只是会传递到button而已,因为最佳响应着依然是redview。
  • 从上面测试结果可以看出,uicontrol会阻断响应链的传递,也就是说在响应uicontol的touches事件时并不会调用nextresponder的对应的方法。
  • 通过在button子类中重写touches的方法,发现如果不调用super的touches对应的方法则不会响应点击事件。由此可以大致推断出uicontrol其子类响应点击原理大致为:根据添加target:action:时设置的uicontrolevents,在touches的合适方法调用target的action方法。

2.3uiscrollview阻断响应链

self.grayview = [[gsgrayview alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth, kscreenheight * 3 / 4)];
    [self.view addsubview:self.grayview];
    
    self.tableview = [[gstableview alloc] initwithframe:cgrectmake(0, 20, kscreenwidth, self.grayview.bounds.size.height / 2)];
    self.tableview.datasource = self;
    self.tableview.backgroundcolor = [uicolor darkgraycolor];
    self.tableview.delegate = self;
    [self.grayview addsubview:self.tableview];
    
    self.redview = [[gsredview alloc] initwithframe:cgrectmake(0, 0, kscreenwidth/2, self.tableview.bounds.size.height/2)];
    [self.tableview addsubview:self.redview];

点击redview
redview -> tableview

  • 从上面测试结果可以得出,uiscrollview也会阻断响应链,也就是说在响应uiscrollview自身对touch的处理方式并不会调用nextresponder对应的方法。
  • 通过重写tableview子类的touches方法,发现如果不调用super的touches对应的方法则不会走tableview:didselectrowatindexpath:方法。由此可以大致推断出uiscrollview其子类是在其touches方法中处理点击事件的。

3.手势

3.1手势的探索以及和touch事件的关系

在上面栗子中的view增加gesturerecognizer:

- (void)addgesture {
    gsgraygesturerecognizer *graygesture = [[gsgraygesturerecognizer alloc] initwithtarget:self action:@selector(grayviewclick:)];
    [self.grayview addgesturerecognizer:graygesture];
    
    gsredgesturerecognizer *redgesture = [[gsredgesturerecognizer alloc] initwithtarget:self action:@selector(redviewclick:)];
    [self.redview addgesturerecognizer:redgesture];
    
    gsbluegesturerecognizer *bluegesture = [[gsbluegesturerecognizer alloc] initwithtarget:self action:@selector(blueviewclick:)];
    [self.blueview addgesturerecognizer:bluegesture];
}

点击redview
打印结果如下图所示:

  • 当通过hittest和pointinside找到最优响应者后,会给gesturerecognizers和相应的view同时发送touchbegin消息,如果找到合适gesturerecognizer则会独有该touches,即调用view的touhecancel消息,接着有gestrerecognizer来响应事件。
  • 上面为默认情况下手势和touches之间的关系,其实我们可以通过gesturerecognizer的属性来控制它们之间的一些关系。
// default is yes. causes touchescancelled:withevent: or pressescancelled:withevent: to be sent to the view for all touches or presses recognized as part of this gesture immediately before the action method is called.
@property(nonatomic) bool cancelstouchesinview; 

// default is no.  causes all touch or press events to be delivered to the target view only after this gesture has failed recognition. set to yes to prevent views from processing any touches or presses that may be recognized as part of this gesture      
@property(nonatomic) bool delaystouchesbegan;         

 // default is yes. causes touchesended or pressesended events to be delivered to the target view only after this gesture has failed recognition. this ensures that a touch or press that is part of the gesture can be cancelled if the gesture is recognized
@property(nonatomic) bool delaystouchesended;        
  • cancelstouchesinview:默认为yes。表示当手势识别成功后,取消最佳响应者对象对于事件的响应,并不再向最佳响应者发送事件。若设置为no,则表示在手势识别器识别成功后仍然向最佳响应者发送事件,最佳响应者仍响应事件。
  • delaystouchesbegan:默认为no,即在手势识别器识别手势期间,触摸对象状态发生变化时,都会发送给最佳响应者,若设置成yes,则在识别手势期间,触摸状态发生变化时不会发送给最佳响应者。
  • delaystouchesended:默认为no。默认情况下当手势识别器未能识别手势时,若此时触摸已经结束,则会立即通知application发送状态为end的touch事件给最佳响应者以调用 touchesended:withevent: 结束事件响应;若设置为yes,则会在手势识别失败时,延迟一小段时间(0.15s)再调用响应者的 touchesended:withevent:。

3.2手势和uicontrol的关系

  • 上面已经说了uicontol会阻断响应链。那么我们再来进一步探索uicontrol的阻断和手势之间的关系。
// button在上面
    self.grayview = [[gsgrayview alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth/2, 400)];
    gsgraygesturerecognizer *graygesture = [[gsgraygesturerecognizer alloc] initwithtarget:self action:@selector(grayviewclick:)];
    [self.grayview addgesturerecognizer:graygesture];
    [self.view addsubview:self.grayview];
    
    gsexpandbutton *expandbutton = [[gsexpandbutton alloc] initwithframe:cgrectmake(30, ktopheight, 100, 100)];
    expandbutton.backgroundcolor = [uicolor redcolor];
    [expandbutton settitle:@"点我啊" forstate:uicontrolstatenormal];
    [expandbutton addtarget:self action:@selector(expandbuttonclick:) forcontrolevents:uicontroleventtouchupinside];
    [self.grayview addsubview:expandbutton];

点击button

  • 从该栗子中可以看出即使下层view添加收拾依然会响应按钮的点击事件。

  • 由此可以猜测原因:
    1. uicontrol及其子类会阻断响应链。(后面验证是错误的)
    2. uicontrol及其子类为最优响应者时会优先处理它们的事件。(后面验证成功)
    • 验证猜测一:
    • 有手势的view上增加一个阻断响应链的view
    self.grayview = [[gsgrayview alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth/2, 400)];
    gsgraygesturerecognizer *graygesture = [[gsgraygesturerecognizer alloc] initwithtarget:self action:@selector(grayviewclick:)];
    [self.grayview addgesturerecognizer:graygesture];
    [self.view addsubview:self.grayview];
    gscancelledtouchview *canceltouchview = [[gscancelledtouchview alloc] initwithframe:cgrectmake(30, ktopheight, 100, 100)];
    [self.grayview addsubview:canceltouchview];

    点击greenview
    • greenview是一个阻断响应链的view(即重新超类touches方法没用调用超类方法),但是依然响应gesturerecognizer的target:action:方法,并且调用touches事件的toucescancelled的方法。因此猜测1是错误的。
    • 验证猜测二:
    • 有收拾的view上增加一个button,button上增加一个view
        // 验证不取消button的touches事件猜测二
    self.grayview = [[gsgrayview alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth/2, 400)];
    gsgraygesturerecognizer *graygesture = [[gsgraygesturerecognizer alloc] initwithtarget:self action:@selector(grayviewclick:)];
    [self.grayview addgesturerecognizer:graygesture];
    [self.view addsubview:self.grayview];
    
    gsexpandbutton *expandbutton = [[gsexpandbutton alloc] initwithframe:cgrectmake(0, 0, kscreenwidth/3, 200)];
    expandbutton.backgroundcolor = [uicolor redcolor];
    [expandbutton settitle:@"点我啊" forstate:uicontrolstatenormal];
    [expandbutton addtarget:self action:@selector(expandbuttonclick:) forcontrolevents:uicontroleventtouchupinside];
    [self.grayview addsubview:expandbutton];
    
    
    self.blueview = [[gsblueview alloc] initwithframe:cgrectmake(0, 0, 100, 100)];
    [expandbutton addsubview:self.blueview];

    点击blueview
    • 点击blueview虽然expandbutton会阻断响应链但是依然会执行在grayview上的手势方法并且会调用touchescancelled方法,因此可以验证猜想二是正确的。
    • 把grayview上的gesturerecognizer去掉,依然不会响应expandbutton上的点击事件,因为最优响应者不是expandbutton。
  • uicontrol及其子类能够执行点击事件而不是走底层的手势的原因为:在识别到相应的gesturerecognizer后如果当前的最优响应者是uicontrol及其子类并且当前的gesturerecognizer不是uicontol上的手势,则会响应uicontrol的target:action:的方法。否则则会响应gesturerecognizer的target:action:的方法。

3.3 手势和uiscrollview的关系

  • uitableview是uiscroll子类的常用类,因此拿uitableview来举栗子。
self.grayview = [[gsgrayview alloc] initwithframe:cgrectmake(0, ktopheight, kscreenwidth, kscreenheight * 3 / 4)];
    gsgraygesturerecognizer *graygesture = [[gsgraygesturerecognizer alloc] initwithtarget:self action:@selector(grayviewclick:)];
    //    graygesture.delaystouchesbegan = yes;
    //    graygesture.cancelstouchesinview = no;
    //    graygesture.delaystouchesended = yes;
    [self.grayview addgesturerecognizer:graygesture];
    [self.view addsubview:self.grayview];
    
    self.tableview = [[gstableview alloc] initwithframe:cgrectmake(0, 20, kscreenwidth, self.grayview.bounds.size.height / 2)];
    self.tableview.datasource = self;
    self.tableview.backgroundcolor = [uicolor darkgraycolor];
    self.tableview.delegate = self;
    [self.grayview addsubview:self.tableview];


点击tableview
当父控件没有手势时

当父控件有手势时

  • 由上面的例子可以得出当uiscrollview为最优响应者并且父控件没有手势时uiscrollview才可以自己处理点击事件。否则被父控件的gesturerecognizer占有。
  • 从上面结果看出当父控件有手势时uiscrollview的touches方法都不执行,类似于设置delaystouchesbegan为yes。
  • 虽然uiscrollview及其子类和uicontrol及其子类类似都可以阻断响应链,但是当uiscrollview及其子类为最优响应者时,如果父控件中有gesturerecognizer依然会被其占有。
uiscrollview点击穿透解决方案

当uiscrollview为最优响应者父控件有手势时,uiscrollview及其子类的点击代理方法和touchesbegan方法不响应。

解决方法:三种解决方式,个人认为第二种为最优解决方案

  • 可以通过给父控件手势设置cancelstouchesinview为no,则会同时响应gesturerecognizer的事件和uiscrollview及其子类的代理方法和touches事件。

  • 给父控件中的手势的代理方法里面做一下判断,当touch的view是我们需要触发的view的时候,return no ,这样就不会走手势方法,而去触发这个touch.view这个对象的方法了。

- (bool)gesturerecognizer:(uigesturerecognizer *)gesturerecognizer shouldreceivetouch:(uitouch *)touch {
    if ([nsstringfromclass([touch.view class])    isequaltostring:@"uitableviewcellcontentview"]) {
        return no;
    }
    return yes;
}
  • 可以通过给uiscrollview及其子类添加gesturerecognizer,从而来调用需要处理的事情。

文章若有不对地方,欢迎批评指正

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网