【发布时间】:2012-03-26 11:35:17
【问题描述】:
我有两个视图,每个视图都包含两个子视图。
只要两个顶视图不重叠,命中检测就可以正常工作。 因此,我可以触摸下图左侧标记为 A 的子视图。
但是,一旦前两个视图重叠,A 视图就无法接收触摸,因为视图 1 位于视图 2“上方”并“吃掉”触摸。
View 1 和 View 2 都检测触摸,因为它们可以四处移动,因此需要检测“在”子视图之间的触摸并做出反应。
这意味着我的两个“顶级视图”检测应该说:“哦,等一下,也许我正在重叠其他视图并且应该将事件传递给它,并且仅当且仅当没有其他观点是“在我之下””。
我该怎么做?
编辑: 谢谢 jaydee3
起初这不起作用,导致无限递归:每个视图都推迟到其兄弟姐妹,而兄弟姐妹又推迟回到初始视图:
- (UIView *) hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView * hit = [super hitTest:point withEvent:event] ;
if (hit == self) {
for (UIView * sibling in self.superview.subviews) {
if (sibling != self) {
CGPoint translated = [self convertPoint:point toView:sibling] ;
UIView * other = [sibling hitTest:translated withEvent:event] ;
if (other) {
return other ;
}
}
}
}
return hit ;
}
所以,我添加了一个“标记集”来跟踪已访问过哪个视图,现在一切正常:)
- (UIView *) hitTest: (CGPoint) point withEvent: (UIEvent *) event {
static NSMutableSet * markedViews = [NSMutableSet setWithCapacity:4] ;
UIView * hit = [super hitTest:point withEvent:event] ;
if (hit == nil) return nil ;
if (hit == self) {
for (UIView * sibling in hit.superview.subviews) {
if (sibling != hit) {
if ([markedViews containsObject:sibling]) {
continue ;
}
[markedViews addObject:sibling] ;
CGPoint translated = [hit convertPoint:point toView:sibling] ;
UIView * other = [sibling hitTest:translated withEvent:event] ;
[markedViews removeObject:sibling] ;
if (other) {
return other ;
}
}
}
}
return hit ;
}
【问题讨论】: