start_time: 2024-04-20 06:18:05 +0800

巧用UIResponder进行事件传递

96
lsb332
IP属地: 浙江
0.6 2016.06.23 17:36 字数 1168

开篇先说点废话吧,最近整个人都很烦躁,也许跟天气有关吧,也很久没有静下来写一些东西了,最近也一直忙着新项目,也很纠接新项目应该采用什么样的结构去写才好迭代、维护。最终按自己的一写想法采用了Controller View ViewHander的模式(有点类似MVVM),因为这个Demo按照这个想法来写的所以这里简单说下,就不过多的讨论这个了,回到主题上UIResponder来,没有说之前我们先看一个图我们开发中经常遇到的:

1.1png

很简单就是在UITableViewCell 放了一个UIButton 那我们怎么样接收这个Button的点击事件? 你第一时间可能会想到Delegate,Block?的确它们都可以实现我们的需求,Delegate我们要多写点代码,Block 如果我们的事件逻辑复杂点就会再赋值时写很多代码,当然你可以用一个简单的Block把处理的业务代封装成方法,再这个调用这方法,也可以把代码弄的简洁点,最重要我一定要考虑循环引用的问题。那我们能不能用UIResponder 传递这个事件呢,在我们想要的地方捕获这个事件呢? 我们先来看看iOS 事件是怎么传递的我们看个图:

1.2.png

如上图,iOS中事件传递首先从App(UIApplication)开始,接着传递到Window(UIWindow),在接着往下传递到View之前,Window会将事件交给GestureRecognizer,如果在此期间,GestureRecognizer识别了传递过来的事件,则该事件将不会继续传递到View去,而是像我们之前说的那样交给Target(ViewController)进行处理。(注:详细原理可以自己进行搜索学习)我们大致知道事件产生最先识别是的 AppDelegate,然后一层层往下找看事件发生那个view上,直到找个这个view,然后看个view 能不能响应这个事件。那我们现在再说说响应者链先看个张图:

Paste_Image.png

我知道了当事触摸事件发生,通过一层层找到的这个View ,找到这个View 后先判断这个view能不能响应这个事件,如果不能那就继续找nextResponder我们看上面图可以看出如果一个View有SuperView 那么这个View的nextResponder 就是他的SuperView,如果没有SuperView 那么它的nextResponder 就是他所在ViewController 然后就这样一直找下去,直到找到或抛出异常。
我们了解这机制后那我们怎么把这个UIButton Click 事件传递出来呢,我们先来给UIResponder 添加一个我们自定义的事件,我就让它传递我们这个事件出去。
#import "UIResponder+Router.h"

@implementation UIResponder (Router)
 // eventName 只是作个标记,当我们需要在一个页面传递个事件时我们可以进区分,userInfo 为了省劲就没有封装,你可以针对性再封装下
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
      [[self nextResponder] routerEventWithName:eventName userInfo:userInfo];
 }
 @end

那我们怎么进行传递呢,那就是我们手动的去让响应者链传递这个事件
我们先看下工程的代码文件:
View
#import "TestView.h"
#import "TestViewTableDataSource.h"

@implementation TestView {
    UITableView *_tableView;
}

 - (instancetype)initWithController:(SBBaseViewController *)controller {
   self = [super initWithController:controller];
   if (self) {
    [self setup];
    }
     return self;
 }

 - (void)setup {

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.rowHeight = 60;
    _tableView.translatesAutoresizingMaskIntoConstraints = NO;
    [_tableView registerClass:[TestViewTableCell class] forCellReuseIdentifier:@"cell"];
    [self addSubview:_tableView];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_tableView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableView)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_tableView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableView)]];

}

- (void)setHandler:(SBBaseHandler *)handler {
    [super setHandler:handler];
    // 把tableViewDataSource 分离出去
    TestViewTableDataSource *tableViewDataSoure = [[TestViewTableDataSource alloc] initWithTableView:_tableView];

    _tableView.dataSource = tableViewDataSoure;
    self.handler.tableDataSource = tableViewDataSoure;
}

- (void)didLoad {
    [self.handler loadData];
}

Controller

#import "TestViewController.h"
#import "TestView.h"
#import "TestViewHandler.h"

@interface TestViewController ()

@end

@implementation TestViewController

- (void)loadView {
    [super loadView];
    TestView *view = [[TestView alloc]initWithController:self];
    TestViewHandler *handler = [[TestViewHandler alloc] init];
    view.handler = handler;
    self.view = view;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"UIResponderEx";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
 }
@end

Handler
#import "TestViewHandler.h"

@implementation TestViewHandler

- (void)loadData {
    NSMutableArray *datasource = [NSMutableArray arrayWithCapacity:10];
    for (int i = 0; i< 10; ++i) {
        [datasource addObject:[NSString stringWithFormat:@"Row number is %d",i]];
    }
    self.tableDataSource.dataSouce = [datasource copy];
}

@end

TableDataSource
#import "SBBaseTableDataSource.h"

@interface TestViewTableDataSource : SBBaseTableDataSource

@end
// 这里为了省劲就没有用单独文件去写,最好还是建两个新文件去比较好
@interface TestViewTableCell : UITableViewCell

@end

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

@implementation TestViewTableDataSource

- (id)initWithTableView:(UITableView *)tableView {
    self = [super initWithTableView:tableView];
    if (self) {
    
    }

    return self;
}

  - (void)setDataSouce:(NSArray *)dataSouce {
    [super setDataSouce:dataSouce];
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TestViewTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.dataSouce[indexPath.row];

    return cell;
}

@end

@implementation TestViewTableCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
       [self setup];
    }
    return self;
}

- (void)setup {
    UIButton *showNumberButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [showNumberButton setTitle:@"Show row number" forState:UIControlStateNormal];
    showNumberButton.backgroundColor = [UIColor purpleColor];
    showNumberButton.layer.cornerRadius = 4;
    showNumberButton.layer.masksToBounds = YES;
    showNumberButton.translatesAutoresizingMaskIntoConstraints = NO;
   [showNumberButton addTarget:self action:@selector(showNumberButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:showNumberButton];

    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[showNumberButton(180)]-20-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(showNumberButton)]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:showNumberButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
}
   //关键代码就在这里, 我们在button click 事件中我再让传递一个事件给响应者链,让响应者链传出去
- (void)showNumberButtonClick:(id)sender {
    // 我们在这个Click事件中去手动让响应者传递一个事件
    [self.nextResponder routerEventWithName:@"showNumber" userInfo:@{@"object":self.textLabel.text}];
}
@end

主要的代码差不多就是这些了,至于他们的基类都是自己封装好一部分,还不怎么完善都是一些自己的想法。就不贴代码稍后把这个Demo放出来。有兴趣的可以下下来看看,如果有我好的想法请联系我:lsb332@163.com
我们先来看看在View 中捕获下事件,在.m 文件我们导入UIResponder+Router.h头文件 然后实现我们自定义的方法

#import "UIResponder+Router.h"
#pragma UIResponder(Router)
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
   UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"View中捕获" message:userInfo[@"object"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
   [alertView show];
}

** 手动传递事件的代码TableDataSource 已经贴出来过了这里就不贴了**
我们看下结果:

1.4.png

我们再来看看在UIViewController 捕获,代码就不贴了看下结果好了:

1.5.png

总结

最重要的思想就是在响应事件方法我们再主动的传递给响应者链一个事件,然后我们合适的地方去响应这个事件
这个也是抛砖引玉的,自己理解的还很肤浅的,现在写出来也算是自己学习的一个笔记吧,这个处理方法也是自己在集成环信中发现的,自己去摸索学习下。
Demo地址 https://github.com/lsb332/UIResponderEX
在这里再说一下自己项目结构,为了减轻UIViewController 重量实行真正的MVC 把View分出来了,从而使ViewController 只负责view 的显示 ,称除等。因为我们项目经常会用到TableView 为了不使View太重再次把这个分离去,使TableView的dataSource 在TableViewSource文件中去实现,然后又给View 建了一个Handler 用来处理业务逻辑,网络请求等,然后又把handler 继承一个网络求的类,这样可就可以处理的网络的请求了,如果handler 处理完数据后可以通过Block 回调给View 或者直接把数据传递给TableViewSource 就可以直接刷新数据,不用再回调给View。这里只是简单的说一下,有兴趣的可以工程里看看,还处在起步结段,如果觉得成熟了再写一篇文章说说吧。

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