概述
響應鏈是支撐app界面交互的基礎,點擊,滑動,旋轉,搖晃背后都離不開響應鏈。
觸發一次事件時,系統會將事件Event放到事件隊列中,由UIApplication從隊列中取得這個Event。
響應者
- 尋找事件的響應者是通過
hitTest
和pointInside
完成的 -
hitTest
調用順序從UIWindow開始,對子視圖一次調用 - 遍歷直到找到響應視圖,逐級返回最終到UIWindow返回此視圖
處理者
UIResponder主要有4個方法來處理事件:
- (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;
如果Responder沒有處理事件,事件會被傳遞。下個傳遞給該對象的nextResponder。如果都沒有處理事件,事件被丟棄。
響應者鏈一直傳遞到AppDelegate:
image.png
- 找到響應者視圖后事件會從此視圖開始沿著響應者鏈nextResponder傳遞,直到找到處理事件的視圖,沒有則被丟棄。
- 如果視圖有父視圖,則nextResponder指向父視圖,如果是根視圖則指向控制器。最終指向AppDelegate。