使用事件響應(yīng)鏈處理事件

概述

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實(shí)現(xiàn)對(duì)象交互

我們可以借用responder chain實(shí)現(xiàn)了一個(gè)自己的事件傳遞鏈。

//UIResponder的分類(lèi)
//.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、創(chuàng)建簽名對(duì)象
    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:@"方法沒(méi)有" reason:info userInfo:nil];
        return nil;
    }
    //3、、創(chuàng)建NSInvocation對(duì)象
    NSInvocation*invocation = [NSInvocation invocationWithMethodSignature:signature];
    //4、保存方法所屬的對(duì)象
    invocation.target = self;
    invocation.selector = aSelector;
    return invocation;
}

@end

在需要響應(yīng)事件的類(lèi)中重載routerEventWithName::方法

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

使用EventProxy類(lèi)來(lái)專(zhuān)門(mén)處理對(duì)應(yīng)的事件

//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 左邊按鈕被點(diǎn)擊啦!",indexPath.section, indexPath.row);
}

- (void)cellMiddleButtonClick:(NSDictionary *)userInfo {
    NSIndexPath *indexPath = userInfo[@"indexPath"];
    NSLog(@"indexPath:section:%ld, row:%ld 中間按鈕被點(diǎn)擊啦!",indexPath.section, indexPath.row);
}

- (void)cellRightButtonClick:(NSDictionary *)userInfo {
    NSIndexPath *indexPath = userInfo[@"indexPath"];
    NSLog(@"indexPath:section:%ld, row:%ld 右邊按鈕被點(diǎn)擊啦!",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的事件中,調(diào)用routerEventWithName:userInfo:方法,就會(huì)調(diào)用到EventProxy類(lèi)中的方法。

@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

總結(jié)

  • 使用這種基于Responder Chain的方式來(lái)傳遞事件,在復(fù)雜UI層級(jí)的頁(yè)面中,可以避免無(wú)謂的delegate聲明。
  • 事件處理的邏輯得到歸攏,在這個(gè)方法里面下斷點(diǎn)就能夠管理所有的事件處理。

參考文章

Using Responders and the Responder Chain to Handle Events
一種基于ResponderChain的對(duì)象交互方式
responderChainDemo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • 2017.4.16 6組家長(zhǎng)陳鳳蘭 #做個(gè)有耐心的媽媽# 陳志朗10歲 踐行打卡 14/30 孩子第三個(gè)30天目標(biāo)...
    陪著孩子一起成長(zhǎng)閱讀 257評(píng)論 0 2
  • 郭相麟 出門(mén)在外冷暖自知,某天下午我的時(shí)間在走錯(cuò)路、繞遠(yuǎn)路,來(lái)回倒騰中度過(guò)! 方向不清晰,依賴著導(dǎo)航給出的方向...
    郭相麟閱讀 304評(píng)論 0 0
  • 親愛(ài)的何老師: 您好! 教了我們?nèi)甑哪欢▽?duì)我們的性格、愛(ài)好十分了解。在課堂上我們是師徒...
    明月旺仔閱讀 488評(píng)論 0 0
  • 2017.8.4 大家一夜的祈禱,換來(lái)多寶咪的平安挺?。?二號(hào)天使曹女士開(kāi)始為多寶咪做二次清潔,用棉簽輕輕擦拭她的...
    風(fēng)和日麗wy閱讀 571評(píng)論 3 7

友情鏈接更多精彩內(nèi)容