前面幾篇分析了 iOS 事件的分發路徑——事件如何找到該處理的 view,又如何沿著響應者鏈逐級傳遞。這篇談的是更前面的一步:攔截。
事件的分發路徑是 Application → Window → 各級 View。既然 flow 的起點在這裡,那麼最安全可靠的攔截位置自然也是這裡。只要在 sendEvent: 中不手動往下傳,事件連進入 hit-test 的機會都不會有。
UIApplication 與 UIWindow 都有 sendEvent: 方法,繼承並改寫它,就能在事件進入系統前先做處理。
假設有個 iPad App,需求是「在非某個特定 view 的區域觸摸時執行某項處理」。直覺做法是在其他每個 view 裡都加判斷,但這樣既容易漏,UI 一改版更是維護惡夢。更好的方式是在 Application 層做一次統一過濾,把 touch 事件轉成通知,讓有興趣的 view 自己訂閱。
#import <UIKit/UIKit.h> extern NSString *const notiScreenTouch; @interface DPApplication : UIApplication @end
#import "DPApplication.h"
NSString *const notiScreenTouch = @"notiScreenTouch";
@implementation DPApplication
- (void)sendEvent:(UIEvent *)event {
if (event.type == UIEventTypeTouches) {
if ([[event.allTouches anyObject] phase] == UITouchPhaseBegan) {
[[NSNotificationCenter defaultCenter]
postNotification:[NSNotification notificationWithName:notiScreenTouch
object:nil
userInfo:[NSDictionary dictionaryWithObject:event forKey:@"data"]]];
}
}
[super sendEvent:event];
}
@end
注意最後一定要呼叫 super,否則整個 App 的事件鏈會斷掉,畫面變成完全無法操作。
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "DPApplication.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv,
NSStringFromClass([DPApplication class]),
NSStringFromClass([AppDelegate class]));
}
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onScreenTouch:)
name:notiScreenTouch
object:nil];
- (void)onScreenTouch:(NSNotification *)notification {
UIEvent *event = [notification.userInfo objectForKey:@"data"];
CGPoint pt = [[[[event allTouches] allObjects] objectAtIndex:0] locationInView:self.button];
NSLog(@"pt.x=%f, pt.y=%f", pt.x, pt.y);
}
事件被靜默地預處理了一遍,原有機制完全沒有被破壞。若某些事件需要被過濾掉,只要在 DPApplication 的 sendEvent: 裡直接不回傳給 super 即可——這也是全域性攔截(例如實作全域的浮層遮罩、統一記錄所有點擊、或做為埋點基礎)最乾淨的切入點。
反過來說,正因為它無所不攔,也要小心效能:sendEvent: 每一個事件都會經過,裡面不要放耗時運算或同步 I/O,否則整機的操作都會變卡。