简单的Router

开发中经常有子视图需要把事件传递给父视图,除了代理和block还有更好的选择,这里记录一下tsaievan的Router.

1.首先实现UIResponder的一个扩展


@interface UIResponder (Router)
- (void)routerWithEventName:(NSString *)eventName userInfo:(NSDictionary *)userInfo;
@end

@implementation UIResponder (Router)
//把事件向上层响应者传递
- (void)routerWithEventName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    if (self.nextResponder) {
         [[self nextResponder] routerWithEventName:eventName userInfo:userInfo];
    }
}
@end

2.在ViewController实现对事件的实际处理


- (void)routerWithEventName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    if ([eventName isEqualToString:YourCustomNameEvent]) {
        NSString * name = userInfo[YourCustomKey];
        NSLog(name);
    }
}

3.在子视图的cell上准备传递事件


- (void)buttonClickAction:(UIButton *)sender {
    [sender routerWithEventName:YourCustomNameEvent userInfo:@{
                                                            YourCustomKey:[self userName],
                                                            }];
}

#MORE 可以断点一步一步的调试一下,事件响应链会把消息一层层向上传递,直到最上层有对象对这个消息负责并响应时,会结束传递