使用事件響應鏈處理事件

2021-09-01 13:02:36 字數 3063 閱讀 2259

我們可以借用responder chain實現了乙個自己的事件傳遞鏈。

//uiresponder的分類

//.h檔案

#import

@inte***ce 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

@end

//nsobject

//.h檔案

#import

@inte***ce nsobject (invocation)

-(nsinvocation *

)createinvocationwithselector:

(sel)aselector;

@end

//.m檔案

#import "nsobject+invocation.h"

@implementation nsobject (invocation)

-(nsinvocation *

)createinvocationwithselector:

(sel)aselector

//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

使用eventproxy類來專門處理對應的事件

#import

@inte***ce eventproxy : nsobject-(

void

)handleevent:

(nsstring *

)eventname userinfo:

(nsdictionary *

)userinfo;

@end

#import "eventproxy.h"

#import "responderchaindefine.h"

#import "uiresponder+router.h"

#import "nsobject+invocation.h"

@inte***ce eventproxy (

)@property

(nonatomic, strong) nsdictionary *eventstrategy;

@end

@implementation eventproxy-(

void

)handleevent:

(nsstring *

)eventname userinfo:

(nsdictionary *

)userinfo -(

void

)cellleftbuttonclick:

(nsdictionary *

)userinfo -(

void

)cellmiddlebuttonclick:

(nsdictionary *

)userinfo -(

void

)cellrightbuttonclick:

(nsdictionary *

)userinfo

#pragma mark - getter & setter

-(nsdictionary

, nsinvocation *

>

*)eventstrategy ;}

return _eventstrategy;

}@end

tableviewcell的事件中,呼叫routereventwithname:userinfo:方法,就會呼叫到eventproxy類中的方法。

@implementation tableviewcell

-(ibaction)leftbuttonclick:

(uibutton *

)sender ];

}-(ibaction)middelbuttonclick:

(uibutton *

)sender ];

}-(ibaction)rightbuttonclick:

(uibutton *

)sender ];

}@end

一種基於responderchain的物件互動方式

responderchaindemo

view處理事件

當乙個view需要處理事件的時候 如果我們設定了ontouchlistener,那麼ontouchlistener裡面的ontouch方法會被呼叫,如果ontouch返回false,則當前的view的ontouchevent方法會被呼叫 如果返回值true,那麼ontouchevent方法不會被呼叫...

perl sdl處理事件

use sdl use sdlx sprite use sdl event use sdl events 畫大地 隨機生成大地的麻點 for my i 1 i 500 i 畫夜空 my sky sdlx sprite new width 400,height 200 sky su ce draw r...

處理事件冒泡

導火線 tr元素繫結了乙個點選事件,tr下面有乙個button元素,此時需要給button元素繫結乙個點選事件,而執行了tr的點選事件.需要把tr的點選事件阻止掉 方案1 在tr執行它的點選事件的時候過濾掉子元素button 菜鳥教程寫的demo 可是我專案中加上addeventlintener監聽...