用戶在使用app的時候,會產生各樣的事件。在iOS中的事件可以分為三種
在iOS中,并不是所有的對象都能處理事件,直接或者間接繼承UIResponder的對象(UIapplication、 UIViewController、UIWindow和所有繼承自UIView的UIKit類)才能對事件進行響應,我們稱呼這些為“響應者對象”;
在UIRecponder中提供了下面的代碼來處理事件:
1 //觸摸事件 2 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; 3 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; 4 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; 5 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; 6 //加速計事件 7 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event; 8 - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event; 9 - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;10 11//遠程控制事件12 - (void)remoteControlReceivedWithEvent:(UIEvent *)event;
那我們就可以用觸摸事件處理的過程來說一下響應者鏈條和響應者對象,在剛才我們說了能對事件進行響應的叫做響應者對象,響應者對象能夠響應、處理事件。而響應者鏈條是由多個響應者對象構成的一個具有層級關系的東西。
比如下圖:
上圖中的view,controller,window,application都是響應者對象,按照箭頭的走向不難看出響應者鏈條的關系:
響應者鏈條可以讓多個響應者同時響應一個觸摸事件;
我在顏色View.m的文件中寫了
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
NSLog(@"顏色View被摸了" );
}
的代碼,當一個view被點擊,它是響應者鏈的開端。整個響應者鏈和事件分發的使命都是找出第一響應者。這個第一響應者是最適合做出響應事件的對象,整個響應過程是這樣子的:
UIAppliction --> UIWiondw -->遞歸找到最適合處理事件的控件-->控件調用touches方法-->判斷是否實現touches方法-->沒有實現默認會將事件傳遞給上一個響應者-->找到上一個響應者
如果view的控制器存在,就傳遞給控制器;如果控制器不存在,則將其傳遞給它的父視圖
在視圖層次結構的最頂級視圖,如果也不能處理收到的事件或消息,則其將事件或消息傳遞給window對象進行處理
如果window對象也不處理,則其將事件或消息傳遞給UIApplication對象
如果UIApplication也不能處理該事件或消息,則將其丟棄
當我在greenViewa.m中touchesBegan的方法中添加代碼
[super touchesBegan:touches withEvent:event];
在圖片中可以看出greenView是Yellow的子視圖,也就是說greenview的下一個響應者時yellow,而greenview.m中調用了super,那么就是說yellow也可以響應touchesBegan的方法,
這樣的話運行結果就是:
2015-11-07 00:35:01.748 ResponderChain[4984:95390] yellowView被摸了
2015-11-07 00:35:01.748 ResponderChain[4984:95390] greenView被摸了
這樣就實現了多個響應者對象響應一個事件。我們可以用這個作出有意思的東西。
參考文獻:
https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiphoneOS/event_delivery_responder_chain/event_delivery_responder_chain.html#//apple_ref/doc/uid/TP40009541-CH4-SW1
新聞熱點
疑難解答