响应链UIResponder事件的交互学习

参考了:https://casatwy.com/responder_chain_communication.html
参考了:https://github.com/qingfengiOS/MutableCellTableView

一般对象之间事件监听我们可以用代理,比如这种情况,控制器的子view(CustomView),上有一个btn点击事件,一般这种事件监听应该交由控制器统一处理

@protocol CustomViewDelegate <NSObject>
- (void)btnClick:(UIButton *)btn;
@end

@interface CustomView : UIView
@property (nonatomic, weak) id<CustomViewDelegate> delegate;
@end

- (IBAction)btnClick:(UIButton *)sender {
    if ([_delegate respondsToSelector:@selector(btnClick:)]) {
        [_delegate btnClick:sender];
    }
}

在控制器中遵守协议,控制器作为代理,然后实现代理方法

// 在控制器中遵守协议
@interface ViewController ()<CustomViewDelegate>
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
    CustomView *customV = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil].firstObject;
    customV.frame = CGRectMake(10, 100, [UIScreen mainScreen].bounds.size.width-10, 250);
    [self.view addSubview:customV];
    // 控制器作为代理
    customV.delegate = self;
}

// 实现代理方法
- (void)btnClick:(nonnull UIButton *)btn {
    NSLog(@"%s,parameter=%@",__func__,btn);
}

然而,发现一个新的思路:使用UIResponder实现事件响应链条传递事件,凡是继承UIResponder的控件都可以比如UIView,我们知道大部分控件都是直接或者间接继承自UIView,比如UIButton,UILabel,UIImageView,UIControl,UISwitch,UIScrollView,UITextView,UITextField,UISearchBar,UIPickerView等等

1.给UIResponder扩展分类

@interface UIResponder (Router)

/**
 凡是继承UIResponder的控件,都可以通过事件响应链条传递事件

 @param eventName 事件名
 @param userInfo 附加参数,nullable可以为空
 */
- (void)routerEventWithName:(NSString *)eventName userInfo:(nullable NSDictionary *)userInfo;


/**
 通过方法SEL生成NSInvocation

 @param selector 方法
 @return Invocation对象
 */
- (NSInvocation *)createInvocationWithSelector:(SEL)selector;

@end

实现

@implementation UIResponder (Router)

- (void)routerEventWithName:(NSString *)eventName userInfo:(nullable NSDictionary *)userInfo{
    
    NSLog(@"UIResponder---eventName=%@,userInfo=%@",eventName,userInfo);
    [[self nextResponder] routerEventWithName:eventName userInfo:userInfo];
}

- (NSInvocation *)createInvocationWithSelector:(SEL)selector{
    
    // 通过方法名创建方法签名 注意:不能使用 [[NSInvocation alloc] init]也不可以用下面这个方法
   // NSMethodSignature *signature = [NSInvocation instanceMethodSignatureForSelector:selector];

    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
    // 通过方法签名创建invocation
    // signature == nil 这里就会崩溃
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setTarget:self];
    [invocation setSelector:selector];
    return invocation;
}

2.发送事件(子view中)

#import "UIResponder+Router.h"

- (IBAction)btnClick:(UIButton *)sender {

    [self routerEventWithName:kEventMyButtonName userInfo: @{@"btnKey": sender.currentTitle}];
}

3.响应处理事件(以控制器为示例)

#import "UIResponder+Router.h"

#pragma mark - Event Response
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    
    NSLog(@"controller---eventName=%@,userInfo=%@",eventName,userInfo);
    // 处理事件
    [self handleEventWithName:eventName parameter:userInfo];
    // 如果有需求 可以把响应链继续传递下去 和super 一样效果
    [[self nextResponder] routerEventWithName:eventName userInfo:userInfo];
    // [super routerEventWithName:eventName userInfo:userInfo];
}

// 处理事件
- (void)handleEventWithName:(NSString *)eventName parameter:(NSDictionary *)parameter{
    
    // 获取invocation对象
    NSInvocation *invocation = self.eventStrategyDictionary[eventName];

    // 设置invocation参数
    // 因为有两个隐藏参数self和_cmd,所有index从2开始
    [invocation setArgument:&parameter atIndex:2];

    // 调用方法
    [invocation invoke];
}

Strategy模式进行更好的事件处理


/// 事件策略字典 key:事件名 value:事件的invocation对象
@property (strong, nonatomic) NSDictionary *eventStrategyDictionary;

#pragma mark - Getter
- (NSDictionary <NSString *, NSInvocation *>*)eventStrategyDictionary {
    if (!_eventStrategyDictionary) {
        NSInvocation *btnInvocation = [self createInvocationWithSelector:@selector(customViewButtonClickWithParameter:)];
        NSInvocation *switchInvocation = [self createInvocationWithSelector:@selector(customViewSwitchValueChangeWithParameter:)];
        NSInvocation *imgInvocation = [self createInvocationWithSelector:@selector(customViewImageViewTapWithParameter:)];
        
        _eventStrategyDictionary = @{ kEventMyButtonName: btnInvocation,
                                      kEventMySwitchName: switchInvocation,
                                      kEventMyImageViewName: imgInvocation
                                    };

    }
    return _eventStrategyDictionary;
}

// 处理button点击事件
- (void)customViewButtonClickWithParameter:(NSDictionary *)parameter{
    
    NSLog(@"%s,parameter=%@",__func__,parameter);
}

使用Strategy模式,即可避免多事件处理场景下导致的冗长if-else语句

对响应链的调用打印

UIResponder---eventName=CustomSwitchEvent,userInfo={
mySwitchKey = 0;
}
UIResponder---eventName=CustomSwitchEvent,userInfo={
mySwitchKey = 0;
}
controller---eventName=CustomSwitchEvent,userInfo={
mySwitchKey = 0;
}
[ViewController customViewSwitchValueChangeWithParameter:],parameter={
mySwitchKey = 0;
}
UIResponder---eventName=CustomSwitchEvent,userInfo={
mySwitchKey = 0;
}
UIResponder---eventName=CustomSwitchEvent,userInfo={
mySwitchKey = 0;
}
AppDelegate---eventName=CustomSwitchEvent,userInfo={
mySwitchKey = 0;
}

由于响应链是一层一层往上传递的,最终会经过AppDelegate,所以如果要对所有事件做统一处理可以在AppDelegate这里

#import "UIResponder+Router.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    
    NSLog(@"AppDelegate---eventName=%@,userInfo=%@",eventName,userInfo);
}
@end

在整个响应链中,任何响应的地方都可以处理,比如添加一些参数(可使用Decorator模式,能够更加有序地收集、归拢数据,降低了工程的维护成本),处理一些业务逻辑

如果页面比较复杂,比如商品详情页,业务逻辑非常多,我们可以新建一个文件(EventProxy),把所有的响应事件放到这个文件进行统一处理,这样就达到了为控制器减负,看起来有点像新的架构

新的架构模式:MVCE(Modle View Controller Event)

EventProxy.h的声明

@interface EventProxy : NSObject

- (void)handleEventWithName:(NSString *)eventName parameter:(NSDictionary *)parameter;

@end

EventProxy.m的实现

#import "EventProxy.h"
#import "UIResponder+Router.h"

NSString *const kEventMyButtonName = @"CustomButtonEvent";
NSString *const kEventMySwitchName = @"CustomSwitchEvent";
NSString *const kEventMyImageViewName = @"CustomImageViewEvent";

@interface EventProxy ()

// 使用Strategy模式,即可避免多事件处理场景下导致的冗长if-else语句
/// 事件策略字典 key:事件名 value:事件的invocation对象
@property (strong, nonatomic) NSDictionary *eventStrategyDictionary;

@end

@implementation EventProxy

- (NSInvocation *)createInvocationWithSelector:(SEL)selector{
    
    // 通过方法名创建方法签名 注意:不能使用 [[NSInvocation alloc] init]也不可以用下面这个方法
    // NSMethodSignature *signature = [NSInvocation instanceMethodSignatureForSelector:selector];
    
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
    // 通过方法签名创建invocation
    // signature == nil 这里就会崩溃
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setTarget:self];
    [invocation setSelector:selector];
    return invocation;
}

#pragma mark - Getter
- (NSDictionary <NSString *, NSInvocation *>*)eventStrategyDictionary {
    if (!_eventStrategyDictionary) {
        NSInvocation *btnInvocation = [self createInvocationWithSelector:@selector(customViewButtonClickWithParameter:)];
        NSInvocation *switchInvocation = [self createInvocationWithSelector:@selector(customViewSwitchValueChangeWithParameter:)];
        NSInvocation *imgInvocation = [self createInvocationWithSelector:@selector(customViewImageViewTapWithParameter:)];
        
        _eventStrategyDictionary = @{ kEventMyButtonName: btnInvocation,
                                      kEventMySwitchName: switchInvocation,
                                      kEventMyImageViewName: imgInvocation
                                      };
        
    }
    return _eventStrategyDictionary;
}

- (void)handleEventWithName:(NSString *)eventName parameter:(NSDictionary *)parameter{
    
    // 获取invocation对象
    NSInvocation *invocation = self.eventStrategyDictionary[eventName];
    
    // 设置invocation参数
    // 因为有两个隐藏参数self和_cmd,所有index从2开始
    [invocation setArgument:&parameter atIndex:2];
    
    // 调用方法
    [invocation invoke];
}

- (void)customViewButtonClickWithParameter:(NSDictionary *)parameter{
    
    NSLog(@"具体方法实现,parameter=%@",parameter);
}
- (void)customViewSwitchValueChangeWithParameter:(NSDictionary *)parameter{
    
    NSLog(@"具体方法实现,parameter=%@",parameter);
}
- (void)customViewImageViewTapWithParameter:(NSDictionary *)parameter{
    
    NSLog(@"具体方法实现,parameter=%@",parameter);
}

控制器中的代码实现

@interface ViewController ()
@property (strong, nonatomic) EventProxy *eventProxy;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化事件代理
    self.eventProxy = [[EventProxy alloc] init];
}

#pragma mark - Event Response
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    
    NSLog(@"controller---eventName=%@,userInfo=%@",eventName,userInfo);
    // 处理事件
    [self.eventProxy handleEventWithName:eventName parameter:userInfo];
    // 把响应链继续传递下去 和super 一样效果
    [[self nextResponder] routerEventWithName:eventName userInfo:userInfo];
    // [super routerEventWithName:eventName userInfo:userInfo];
}
@end

这样控制器把事件的处理交给eventProxy去处理,这样控制器是不是很清爽呢,是不是很像MVCE(Modle View Controller Event)

总结一下:

  • 1.在子view中发送事件
  • 2.一般在控制器中处理事件,也可以发送给一个专门对象eventProxy进行处理这个事件
  • 3.如果有需要可以继续传给其他地方进行处理,比如父控件,AppDelegate

demo下载

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

推荐阅读更多精彩内容