只要你寫過稍微複雜的介面,遲早會遇到這個問題:一個 view 蓋在另一個 view 上面,但你想讓被蓋住的那個收到點擊。這正是重寫 hitTest:withEvent: 最典型的用途。本文從系統預設行為談到三個實際需求,把這個機制講透。
假設畫面上有 viewA 與 viewB。如果你不重寫 hitTest,系統會先問 viewA,再問 viewB。這個過程與下面這段「重寫後的程式碼」邏輯完全相同:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if ([self pointInside:point withEvent:event]) {
} else {
return nil;
}
for (UIView *subView in self.subviews) {
if ([subView hitTest:point withEvent:event] != nil) {
return subView;
}
}
return self;
}
換句話說,每個 UIView 的預設 hitTest 都做著這四件事:先判斷觸摸點是否在自己身上;不在就回傳 nil;在就從後往前問每個子視圖;都沒人要就自己接下。
因為有些情況預設邏輯無法滿足。最常見的動機是穿透上層 view,讓 touch 事件能到達被遮住的下方 view。
例如 viewB 完全蓋住了 viewA,但你希望點擊時由 viewA 來響應。做法是讓 viewA 直接回傳自己,跳過對子視圖的遞迴:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if ([self pointInside:point withEvent:event]) {
NSLog(@"in view A");
return self;
} else {
return nil;
}
}
這樣點擊就被 viewA 攔下來,viewB 完全收不到。
看一個更具體的結構:
Window
└─ ViewA
├─ ButtonA
└─ ViewB
└─ ButtonB
層級關係是:ViewB 完全蓋住了 ButtonA,ButtonB 則在 ViewB 之上。需求有三個:
點擊 ButtonB 的區域時,系統從 ViewA 開始依序呼叫 hitTest,pointInside 的結果依次是:
ButtonB 的子視圖全部回傳 nil,於是 ButtonB 自己成為處理物件。接著觸發 touches 系列方法,執行 ButtonB 綁定的動作,訊息鏈到此結束。
由於 hitTest 的尋找是從父 view 開始的,我們可以在 ViewA 的 hitTest 裡做一個「特判」:如果觸摸點落在 ButtonA 上,就直接回傳 ButtonA。
#pragma mark - hitTest
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
// 當觸摸點落在 _btn 上,直接回傳 _btn
CGPoint btnPointInA = [_btn convertPoint:point fromView:self];
if ([_btn pointInside:btnPointInA withEvent:event]) {
return _btn;
}
// 否則走預設邏輯
return [super hitTest:point withEvent:event];
}
關鍵在於座標系轉換:point 是相對於 ViewA 的座標,必須先轉成 ButtonA 座標系下的點,才能正確呼叫 pointInside。少了這步,判斷永遠是錯的。
這樣一來,點擊落在 ButtonA 上時,訊息被攔在 ViewA 這層,ViewB 收不到,而 ButtonA 正常觸發。
ViewB 只要覆寫 touches 系列方法,在自己處理完之後,把訊息往下傳給下一個響應者(也就是父 view)即可:
// 在 ViewB 中
#pragma mark - touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"B - touchesBegan..");
// 傳給父 view 或包含它的 viewController
[self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"B - touchesMoved..");
[self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"B - touchesEnded..");
[self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"B - touchesCancelled..");
[self.nextResponder touchesBegan:touches withEvent:event];
}
於是 ViewA 這邊就能收到:
// 在 ViewA 中
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"A - touchesBegan..");
}
這段範例程式碼裡四個方法都轉發成 touchesBegan,原意是示範「往父層透傳」的機制。實務上請對應轉發同類事件(touchesMoved 轉 touchesMoved,餘類推),否則手勢狀態會錯亂。
最直接的方式是關掉使用者互動:
viewB.userInteractionEnabled = NO;
另一種做法是覆寫 pointInside 直接回傳 NO,讓 hitTest 在這一層就放棄:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
// 本 view 不響應用戶事件
return NO;
}
[super hitTest:point withEvent:event] 作為退路。