【问题标题】:UITouch on overlapping UIViews重叠 UIView 上的 UITouch
【发布时间】: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 ;
}

【问题讨论】:

    标签: ios uiview uitouch


    【解决方案1】:

    为您的视图创建一个自定义子类(包含其他两个子视图)并为其覆盖hitTest: 方法。在该方法中,检查 hitTest 视图是否是两个子视图之一,否则返回 nil。因此,您周围的视图中的所有触摸都将被忽略。导致触摸下面的视图,它可以自己处理。

    //编辑:(您可以通过调用UIView* view = [super hitTest:withEvent:]; 获得hitTest 视图。)

    //edit2:我想更多的是这样的::)

    - (UIView *) hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        UIView * hit =  [super hitTest:point withEvent:event] ;
    
        if (hit == self) {
            return nil;
        }
    
        return hit ;
    }
    

    ;)

    【讨论】:

    • 那行不通,因为这会阻止顶部视图处理任何事件。在我编辑的问题中,我提供了现在可以工作的代码。再次感谢。
    • aah 我不知道你也需要接触这些观点。好的。不客气。
    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多