使用事件响应链处理事件

概述

Apps receive and handle events using responder objects. A responder object is any instance of the UIResponder class, and common subclasses include UIView, UIViewController, and UIApplication. Responders receive the raw event data and must either handle the event or forward it to another responder object. When your app receives an event, UIKit automatically directs that event to the most appropriate responder object, known as the first responder.

Unhandled events are passed from responder to responder in the active responder chain, which is the dynamic configuration of your app’s responder objects. Figure 1 shows the responders in an app whose interface contains a label, a text field, a button, and two background views. The diagram also shows how events move from one responder to the next, following the responder chain.

Figure 1.png

If the text field does not handle an event, UIKit sends the event to the text field’s parent UIView object, followed by the root view of the window. From the root view, the responder chain diverts to the owning view controller before directing the event to the window. If the window cannot handle the event, UIKit delivers the event to the UIApplication object, and possibly to the app delegate if that object is an instance of UIResponder and not already part of the responder chain.

基于ResponderChain实现对象交互

我们可以借用responder chain实现了一个自己的事件传递链。

//UIResponder的分类
//.h文件
#import <UIKit/UIKit.h>

@interface UIResponder (Router)

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo;

@end

//.m文件
#import "UIResponder+Router.h"

@implementation UIResponder (Router)

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    [[self nextResponder] routerEventWithName:eventName userInfo:userInfo];
}

@end
//NSObject
//.h文件
#import <Foundation/Foundation.h>

@interface NSObject (Invocation)

- (NSInvocation *)createInvocationWithSelector:(SEL)aSelector;

@end

//.m文件

#import "NSObject+Invocation.h"

@implementation NSObject (Invocation)

- (NSInvocation *)createInvocationWithSelector:(SEL)aSelector {
    //1、创建签名对象
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:aSelector];
    
    //2、判断传入的方法是否存在
    if (signature==nil) {
        //传入的方法不存在 就抛异常
        NSString*info = [NSString stringWithFormat:@"-[%@ %@]:unrecognized selector sent to instance",[self class],NSStringFromSelector(aSelector)];
        @throw [[NSException alloc] initWithName:@"方法没有" reason:info userInfo:nil];
        return nil;
    }
    //3、、创建NSInvocation对象
    NSInvocation*invocation = [NSInvocation invocationWithMethodSignature:signature];
    //4、保存方法所属的对象
    invocation.target = self;
    invocation.selector = aSelector;
    return invocation;
}

@end

在需要响应事件的类中重载routerEventWithName::方法

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    [self.eventProxy handleEvent:eventName userInfo:userInfo];
}

使用EventProxy类来专门处理对应的事件

//EventProxy.h
#import <Foundation/Foundation.h>

@interface EventProxy : NSObject

- (void)handleEvent:(NSString *)eventName userInfo:(NSDictionary *)userInfo;

@end

//EventProxy.m
#import "EventProxy.h"
#import "ResponderChainDefine.h"
#import "UIResponder+Router.h"
#import "NSObject+Invocation.h"

@interface EventProxy ()


@property (nonatomic, strong) NSDictionary *eventStrategy;

@end

@implementation EventProxy

- (void)handleEvent:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    
    NSInvocation *invocation = self.eventStrategy[eventName];
    [invocation setArgument:&userInfo atIndex:2];
    [invocation invoke];
}

- (void)cellLeftButtonClick:(NSDictionary *)userInfo {
    NSIndexPath *indexPath = userInfo[@"indexPath"];
    NSLog(@"indexPath:section:%ld, row:%ld 左边按钮被点击啦!",indexPath.section, indexPath.row);
}

- (void)cellMiddleButtonClick:(NSDictionary *)userInfo {
    NSIndexPath *indexPath = userInfo[@"indexPath"];
    NSLog(@"indexPath:section:%ld, row:%ld 中间按钮被点击啦!",indexPath.section, indexPath.row);
}

- (void)cellRightButtonClick:(NSDictionary *)userInfo {
    NSIndexPath *indexPath = userInfo[@"indexPath"];
    NSLog(@"indexPath:section:%ld, row:%ld 右边按钮被点击啦!",indexPath.section, indexPath.row);
}

#pragma mark - getter & setter
- (NSDictionary <NSString *, NSInvocation *>*)eventStrategy {
    if (!_eventStrategy) {
        _eventStrategy = @{
                           kTableViewCellEventTappedLeftButton:[self createInvocationWithSelector:@selector(cellLeftButtonClick:)],
                           kTableViewCellEventTappedMiddleButton:[self createInvocationWithSelector:@selector(cellMiddleButtonClick:)],
                           kTableViewCellEventTappedRightButton:[self createInvocationWithSelector:@selector(cellRightButtonClick:)]
                           };
    }
    return _eventStrategy;
}

@end

TableViewCell的事件中,调用routerEventWithName:userInfo:方法,就会调用到EventProxy类中的方法。

@implementation TableViewCell

- (IBAction)leftButtonClick:(UIButton *)sender {
    [self routerEventWithName:kTableViewCellEventTappedLeftButton userInfo:@{@"indexPath":self.indexPath}];
}

- (IBAction)middelButtonClick:(UIButton *)sender {
    [self routerEventWithName:kTableViewCellEventTappedMiddleButton userInfo:@{@"indexPath":self.indexPath}];
}

- (IBAction)rightButtonClick:(UIButton *)sender {
    [self routerEventWithName:kTableViewCellEventTappedRightButton userInfo:@{@"indexPath":self.indexPath}];
}

@end

总结

  • 使用这种基于Responder Chain的方式来传递事件,在复杂UI层级的页面中,可以避免无谓的delegate声明。
  • 事件处理的逻辑得到归拢,在这个方法里面下断点就能够管理所有的事件处理。

参考文章

Using Responders and the Responder Chain to Handle Events
一种基于ResponderChain的对象交互方式
responderChainDemo

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 2017.4.16 6组家长陈凤兰 #做个有耐心的妈妈# 陈志朗10岁 践行打卡 14/30 孩子第三个30天目标...
    陪着孩子一起成长阅读 238评论 0 2
  • 郭相麟 出门在外冷暖自知,某天下午我的时间在走错路、绕远路,来回倒腾中度过! 方向不清晰,依赖着导航给出的方向...
    郭相麟阅读 268评论 0 0
  • 亲爱的何老师: 您好! 教了我们三年的您一定对我们的性格、爱好十分了解。在课堂上我们是师徒...
    明月旺仔阅读 426评论 0 0
  • 2017.8.4 大家一夜的祈祷,换来多宝咪的平安挺住! 二号天使曹女士开始为多宝咪做二次清洁,用棉签轻轻擦拭她的...
    风和日丽wy阅读 517评论 3 7