iOS 响应链原理与应用

前言

iOS响应者链是支撑App界面交互的重要基础,点击、滑动、旋转、摇晃等都离不开其背后的响应者链,所以每个iOS开发人员都应该彻底掌握响应者链的响应逻辑。在iOS中不是任何对象都能处理事件, 只有继承了UIResponder的对象才能接收并处理事件,我们称为响应者对象UIApplication,UIViewController,UIView都继承自UIResponder,因此他们都是响应者对象, 都能够接收并处理事件,响应链就是由不同响应对象组成的层次结构。

iOS中的事件

  • 触摸事件(比如用户点击和滑动屏幕等)。
  • 运动事件(比如重力感应和摇一摇等)。
  • 远程控制事件(比如用耳机上的按键控制手机音量等)。
    这里我们所探讨的是最常用的触摸事件。我们在使用手机时,在屏幕上点击或者滑动一下,都会得到相应的处理结果。那这些交互到底是怎样传递和响应的呢?

事件的产生

iOS系统中有一个UITouch对象,当手指触碰到屏幕,就会对应生成UITouch对象,每个UITouch对象记录了触摸的一些信息,包括触摸发生的时间、触摸在视图或窗口中的位置、触摸的次数、触摸所处的视图、窗口等信息。
UIResponder是iOS中用于处理用户事件的API,可以处理触摸事件,主要是使用下面的方法:

// 触摸开始
- (void)touchesBegan:(NSSet *)touches withEvent:(nullable UIEvent *)event;
// 触摸移动
- (void)touchesMoved:(NSSet *)touches withEvent:(nullable UIEvent *)event;
// 触摸取消(在触摸结束之前)
// 某个系统事件(例如电话呼入)会打断触摸过程
- (void)touchesEnded:(NSSet *)touches withEvent:(nullable UIEvent *)event;
// 触摸结束
- (void)touchesCancelled:(NSSet *)touches withEvent:(nullable UIEvent *)event;

UIResponder不只用来接收事件,还可以处理和传递对应的事件,如果当前响应者不能处理,则转发给其他合适的响应者处理。
当手指触摸到屏幕的时候,系统会将该事件加入到由UIAppliction管理的对了中,队列是先进先出,在取事件时会取出最前面的事件,将之分发出去以便处理,第一个接受事件的对象是窗口对象(UIWindow),系统会调用下面的两个方法:

- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;   // recursively calls -pointInside:withEvent:. point is in the receiver's coordinate system
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;   // default returns YES if point is in bounds

用来确定哪个视图应该接受触摸事件,hitTest函数会返回最佳响应者对象,那怎样判断是否返回呢?在hitTest函数内还会调用pointInside方法,用来判断触摸点是否在当前视图的坐标范围内,若不在范围,则返回nil,若在范围且无子视图,则返回自身作为响应者,若在范围且有子视图可,则遍历子视图,再调用上面两个方法进行判断,直到找到的视图可以响应事件,并且当前视图没有子视图,那么当前视图就是第一响应者。

事件响应

找到了最合适的view接受事件,那是不是说该view一定会响应那个触摸事件呢?答案是否定的,上面我们提到过UIResponder不仅能接受事件,还可以处理和传递事件,也就是说最合适的View也可以将事件按照响应链向下传递,将事件交给下一个响应者去处理。
响应者链是由多个响应者对象链接起来的链,UIResponder有一个属性

@property(nonatomic, readonly, nullable) UIResponder *nextResponder;
//打印响应者链
- (IBAction)click:(id)sender {
    UIResponder *res = sender;
    while (res) {
        NSLog(@"*************************************\n%@",res);
        res = [res nextResponder];
    }
}

在找到最合适的响应者后,会调用自己的touches方法处理事件,如果该响应者不能处理事件,则沿着响应链向向上查找。如果当前view是控制器的view,那么控制器就是上一个响应者,事件就传递给控制器;如果当前view不是控制器的view,那么父视图就是当前view的上一个响应者,事件就传递给它的父视图,如果控制器也不能处理收到的事件或消息,则其将事件或消息传递给window对象进行处理,如果window对象也不处理,则其将事件或消息传递给UIApplication对象,如果UIApplication也不能处理该事件或消息,则将其丢弃。
在响应链中,如果某个控件实现了touches方法且没有调用[super touchesBegan:touches withEvent:event],那事件就由该控件处理不会再传递了,如果调用了就会把事件抛给响应链上的上一个响应者。

一个事件多个对象处理

因为系统默认做法是把事件上抛给父控件,所以可以通过重写自己的touches方法和父控件的touches方法来达到一个事件多个对象处理的目的

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
// 1.自己先处理事件...
NSLog(@"do somthing...");
// 2.再调用系统的默认做法,再把事件交给上一个响应者处理
[super touchesBegan:touches withEvent:event]; 
}

事件拦截

最近接手一个项目,以前App是必须注册或者第三方登录才可以使用,现在希望不登录也可以浏览App里面的内容,在需要登录的地方跳转到登录页。如果在原有基础上去加判断登录的逻辑,我们需要在很多地方都要去写判断的代码,这样很费时费力,而且还会没有兼顾到的地方,那我们该怎样处理呢?我的想法是:因为很多需要登录的操作都是有按钮触发的,所以我为UIButton添加一个分类,分类中将按钮点击事件进行替换,在替换的方法中判断,可以选择的去执行判断登录逻辑的方法, 或者正常走按钮的点击事件。代码如下:

#import 

@interface UIButton (ClickAction)

@end

#import "UIButton+ClickAction.h"
#import 

@implementation UIButton (ClickAction)
+ (void)load{
    [super load];
    //拿到sendAction方法,
    Method oldObjectAtIndex =class_getInstanceMethod([UIButton class],@selector(sendAction:to:forEvent:));
    //定义一个新的方法custom_sendAction
    Method newObjectAtIndex =class_getInstanceMethod([UIButton class], @selector(custom_sendAction:to:forEvent:));
    //交换两个方法的指针
    method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    
}

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
    [super sendAction:action to:target forEvent:event];
}

- (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
     NSString *selectStr = NSStringFromSelector(action);
    selectStr = [selectStr substringToIndex:selectStr.length-1];
    if ([selectStr isEqualToString:@"click"]) {
        NSLog(@"判断是否登录逻辑");
    }else{
        [self custom_sendAction:action to:target forEvent:event];
        //调用custom_sendAction方法,其实指针是指向的原来的sendAction方法
    }
}

扩大Button点击范围

在开发中我们经常会遇到,点击一个带背景图片的按钮,如果图片过小那按钮点击区域也会很小,不好响应点击事件,这时我们会怎么做呢?话不多说看下面代码:

#import 

@interface UIButton (ClickAction)

@end

#import "UIButton+ClickAction.h"
@implementation UIButton (ClickAction)
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }
    //将上下左右都扩展10个像素,有- 号代表向外扩展,无-号代表向内收缩。
    CGRect touchRect = CGRectInset(self.bounds, -10, -10);
    if (CGRectContainsPoint(touchRect, point)) {
        for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
            CGPoint convertedPoint = [subview convertPoint:point fromView:self];
            UIView *hitTestView = [subview hitTest:convertedPoint withEvent:event];
            if (hitTestView) {
                return hitTestView;
            }
        }
        return self;
    }
    return nil;
}

@end

你可能感兴趣的:(iOS 响应链原理与应用)