1. 響應(yīng)者對(duì)象(UIResponder)
學(xué)習(xí)觸摸事件首先要了解一個(gè)比較重要的概念-響應(yīng)者對(duì)象(UIResponder)轴或。
在iOS中不是任何對(duì)象都能處理事件冷尉,只有繼承了UIResponder的對(duì)象才能接受并處理事件,我們稱之為“響應(yīng)者對(duì)象”瞳脓。
那么為什么繼承自UIResponder的類就能夠接收并處理事件呢灭返?
因?yàn)閁IResponder中提供了以下4個(gè)對(duì)象方法來(lái)處理觸摸事件汤徽。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event;
- (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches NS_AVAILABLE_IOS(9_1);
看下官方說(shuō)明:意思就是responder要重載這四個(gè)方法,也可能會(huì)接收到其他的觸摸脂新,必須手動(dòng)取消這些觸摸保證正確的行為...語(yǔ)言功底太差挪捕,湊合看吧
// Generally, all responders which do custom touch handling should override all four of these methods.
// Your responder will receive either touchesEnded:withEvent: or touchesCancelled:withEvent: for each
// touch it is handling (those touches it received in touchesBegan:withEvent:).
// *** You must handle cancelled touches to ensure correct behavior in your application. Failure to
// do so is very likely to lead to incorrect behavior or crashes.
所以UIApplication、UIWindow争便、UIView都能接收觸摸事件
2. 觸摸事件
當(dāng)用戶點(diǎn)擊屏幕后级零,UIApplication 先響應(yīng)事件,然后傳遞給UIWindow始花。如果window可以響應(yīng)妄讯。就開(kāi)始遍歷window的subviews孩锡。遍歷的過(guò)程中,如果第一個(gè)遍歷的view1可以響應(yīng)亥贸,那就遍歷這個(gè)view1的subviews(依次這樣不停地查找躬窜,直至查找到合適的響應(yīng)事件view)。如果view1不可以響應(yīng)炕置,那就開(kāi)始對(duì)view2進(jìn)行判斷和子視圖的遍歷荣挨。依次類推view3,view4…… 如果最后沒(méi)有找到合適的響應(yīng)view朴摊,這個(gè)消息就會(huì)被拋棄默垄。(整個(gè)遍歷的過(guò)程就是樹的先序遍歷)。過(guò)程如下圖:
參考鏈接:
http://www.reibang.com/p/2e074db792ba
https://blog.csdn.net/hello_hwc/article/details/49176867
https://blog.csdn.net/mushaofeng1990/article/details/62434349