iOS 响应链探索-UIResponder

首先要先了解响应者对象UIResponder,只有继承UIResponder的的类,才能处理事件。

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIApplication : UIResponder

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusItem, CALayerDelegate>

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIViewController : UIResponder <NSCoding, UIAppearanceContainer, UITraitEnvironment, UIContentContainer, UIFocusEnvironment>

我们可以看出UIApplication,UIView,UIViewController都是继承自UIResponder类,可以响应和处理事件。

我们下边就来探索一下 响应链
首先 我们分别在自定义的UIWindow,UIView,UIViewController的View
中复写下边几个方法,添加打印 ,看一下打印顺序

// 判断一个点是否落在范围内
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event{
    BOOL isInside = [super pointInside:point withEvent:event];
    SGTLog(@" -------- pointInside  point %@ isInside %d Event %@",NSStringFromCGPoint(point),isInside,event);
    return isInside;
}
// 此方法返回的View是本次点击事件需要的最佳View
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event{
    SGTLog(@" -------- hitTest  point %@  Event %@",NSStringFromCGPoint(point),event);
    return [super hitTest:point withEvent:event];
}
//开始触摸
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    SGTLog(@"-----  touchesBegan  touches %@  event %@",touches,event);
}
//滑动
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    SGTLog(@" ----  touchesMoved   touches %@  event %@",touches,event);
}
//触摸结束
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    SGTLog(@"  ----  touchesEnded    touches %@  event %@",touches,event);
}
//触摸取消
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    SGTLog(@" ----  touchesCancelled    touches %@  event %@",touches,event);
}
- (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches{
    SGTLog(@" ----  touchesEstimatedPropertiesUpdated   touches %@ ",touches);
}

点击屏幕输出日志如下:

2019-04-27 10:32:29.795751+0800 ResponderDemo[67074:1346842] 
-[SGTWindow hitTest:withEvent:] [SGTWindow.m  Line:34]
 -------- fitView <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>>
2019-04-27 10:32:29.796317+0800 ResponderDemo[67074:1346842] 
-[SGTWindow hitTest:withEvent:] [SGTWindow.m  Line:21]
 -------- hitTest  point {173, 176.66667175292969}  Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.809877+0800 ResponderDemo[67074:1346842] 
-[SGTWindow pointInside:withEvent:] [SGTWindow.m  Line:16]
 -------- pointInside  point {173, 176.66667175292969} isInside 1 Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.810082+0800 ResponderDemo[67074:1346842] 
-[SGTBaseView hitTest:withEvent:] [SGTBaseView.m  Line:22]
 -------- hitTest  point {173, 176.66667175292969}  Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.810289+0800 ResponderDemo[67074:1346842] 
-[SGTBaseView pointInside:withEvent:] [SGTBaseView.m  Line:17]
 -------- pointInside  point {173, 176.66667175292969} isInside 1 Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.810448+0800 ResponderDemo[67074:1346842] 
-[OrangeView hitTest:withEvent:] [OrangeView.m  Line:24]
 -------- hitTest  point {-97, 26.666671752929688}  Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.810640+0800 ResponderDemo[67074:1346842] 
-[OrangeView pointInside:withEvent:] [OrangeView.m  Line:19]
 -------- pointInside  point {-97, 26.666671752929688} isInside 0 Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.810813+0800 ResponderDemo[67074:1346842] 
-[RedView hitTest:withEvent:] [RedView.m  Line:25]
 -------- hitTest  point {73, 76.666671752929688}  Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.811021+0800 ResponderDemo[67074:1346842] 
-[RedView pointInside:withEvent:] [RedView.m  Line:20]
 -------- pointInside  point {73, 76.666671752929688} isInside 1 Event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
)}
2019-04-27 10:32:29.811395+0800 ResponderDemo[67074:1346842] 
-[SGTBaseView hitTest:withEvent:] [SGTBaseView.m  Line:35]
 -------- fitView <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>>
2019-04-27 10:32:29.811686+0800 ResponderDemo[67074:1346842] 
-[SGTWindow hitTest:withEvent:] [SGTWindow.m  Line:34]
 -------- fitView <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>>
2019-04-27 10:32:29.814371+0800 ResponderDemo[67074:1346842] 
-[RedView touchesBegan:withEvent:] [RedView.m  Line:48]
 -----  touchesBegan  touches {(
    <UITouch: 0x7fcf04d03df0> phase: Began tap count: 1 force: 0.000 window: <SGTWindow: 0x7fcf04d032f0; baseClass = UIWindow; frame = (0 0; 375 812); gestureRecognizers = <NSArray: 0x600002abf510>; layer = <UIWindowLayer: 0x6000024f3c40>> view: <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>> location in window: {173, 176.66665649414062} previous location in window: {173, 176.66665649414062} location in view: {73, 76.666656494140625} previous location in view: {73, 76.666656494140625}
)}  event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
    <UITouch: 0x7fcf04d03df0> phase: Began tap count: 1 force: 0.000 window: <SGTWindow: 0x7fcf04d032f0; baseClass = UIWindow; frame = (0 0; 375 812); gestureRecognizers = <NSArray: 0x600002abf510>; layer = <UIWindowLayer: 0x6000024f3c40>> view: <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>> location in window: {173, 176.66665649414062} previous location in window: {173, 176.66665649414062} location in view: {73, 76.666656494140625} previous location in view: {73, 76.666656494140625}
)}
2019-04-27 10:32:29.920262+0800 ResponderDemo[67074:1346842] 
-[RedView touchesEnded:withEvent:] [RedView.m  Line:56]
  ----  touchesEnded    touches {(
    <UITouch: 0x7fcf04d03df0> phase: Ended tap count: 1 force: 0.000 window: <SGTWindow: 0x7fcf04d032f0; baseClass = UIWindow; frame = (0 0; 375 812); gestureRecognizers = <NSArray: 0x600002abf510>; layer = <UIWindowLayer: 0x6000024f3c40>> view: <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>> location in window: {173, 176.66665649414062} previous location in window: {173, 176.66665649414062} location in view: {73, 76.666656494140625} previous location in view: {73, 76.666656494140625}
)}  event <UITouchesEvent: 0x6000016f47e0> timestamp: 201623 touches: {(
    <UITouch: 0x7fcf04d03df0> phase: Ended tap count: 1 force: 0.000 window: <SGTWindow: 0x7fcf04d032f0; baseClass = UIWindow; frame = (0 0; 375 812); gestureRecognizers = <NSArray: 0x600002abf510>; layer = <UIWindowLayer: 0x6000024f3c40>> view: <RedView: 0x7fcf04e0afc0; frame = (100 100; 200 100); layer = <CALayer: 0x6000024b1220>> location in window: {173, 176.66665649414062} previous location in window: {173, 176.66665649414062} location in view: {73, 76.666656494140625} previous location in view: {73, 76.666656494140625}
)}

我们看到 主要应用到下边两个方法

// 此方法返回的View是本次点击事件需要的最佳View
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;

// 判断一个点是否落在范围内
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

这个两个方法的作用是寻找到最合适的View去响应事件,我们先了解下事件的分发和传递,更便于我们了解流程:

1.当iOS程序中发生触摸事件后,系统会将事件加入到UIApplication管理的一个任务队列中
2.UIApplication将处于任务队列最前端的事件向下分发。即UIWindow。
3.UIWindow将事件向下分发,即UIView。
4.UIView首先看自己是否能处理事件,触摸点是否在自己身上。如果能,那么继续寻找子视图。
5.遍历子控件,重复以上两步。
6.如果没有找到,那么自己就是事件处理者。如果
7.如果自己不能处理,那么不做任何处理。
其中 UIView不接受事件处理的情况主要有以下三种
1)alpha <0.01
2)userInteractionEnabled = NO
3.hidden = YES.

结合我们的日志输出,我们可以看到,首先调起的是Widow的hitTest:withEvent:方法,满足(alpha >=0.01
&& userInteractionEnabled == YES && hidden == NO.) 调用pointInside:withEvent:方法判断是否在当前响应区域,如果在当前区域,从后往前轮询自己的子视图,调用子视图的hitTest:withEvent:方法,一直找到最合适的响应View,返回,代码如下:

// 此方法返回的View是本次点击事件需要的最佳View
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event{
    SGTLog(@" -------- hitTest  point %@  Event %@",NSStringFromCGPoint(point),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
            SGTLog(@" -------- fitView %@",fitView);
            return fitView;
        }
    }
    // 循环结束,表示没有比自己更合适的view
    return self;
//    return [super hitTest:point withEvent:event];
}

响应者链及nextResponder

响应者链

响应链是从最合适的view开始传递,处理事件传递给下一个响应者,响应者链的传递方法是事件传递的反方法,如果所有响应者都不处理事件,则事件被丢弃。我们通常用响应者链来获取上几级响应者,方法是UIResponder的nextResponder方法。
我们从上边日志中找到最合适的View是RedView,所以RedView是响应者,最终实现的是RedView的touchesBegan:withEvent:及touchesEnded:withEvent:方法,我们可以在RedView的touchesBegan或者其他方法中处理逻辑,另外如果我们想把事件传递到RedView的父视图,可以使用nextResponder来获取,使用[self.nextResponder touchesBegan:touches withEvent:event];方法可以把响应传递到下一个响应者(一般为父视图)

//开始触摸
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
    SGTLog(@" -----  touchesBegan  touches %@  event %@",touches,event);
    [super touchesBegan:touches withEvent:event];
    [self.nextResponder touchesBegan:touches withEvent:event];
}
nextResponder

我们有时候可能会通过nextResponder来查找控件的父视图控件。

// 通过遍历view上的响应链来查找SuperView
    UIResponder *responder = self.nextResponder;
    while (responder) {
        if ([responder isKindOfClass:[SGTBaseView class]]) {
            SGTBaseView *superView = (SGTBaseView *)responder;
            SGTLog(@" -------- superView %@ ",superView);
            break;
        }
        responder = responder.nextResponder;
    }

demo地址

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容