OGeek|极客世界-中国程序员成长平台

标题: ios - 重叠 UIView 上的 UITouch [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:37
标题: ios - 重叠 UIView 上的 UITouch

我有两个 View ,每个 View 都包含两个 subview 。

只要两个顶 View 不重叠,命中检测就可以正常工作。 因此,我可以触摸下图左侧标记为 A 的 subview 。

但是,一旦前两个 View 重叠,A View 就无法接收触摸,因为 View ​​1 位于 View 2“上方”并“吃掉”触摸。

View 1 和 View 2 都检测触摸,因为它们可以移动,因此需要检测“在” subview 之间的触摸并使用react。

这意味着我的两个“顶级 View ”检测应该说:“哦,等一下,也许我正在重叠其他 View ,应该将事件传递给它,并且仅当且仅当没有其他观点是“在我之下””。

我该怎么做? enter image description here

编辑: 谢谢jaydee3

起初这不起作用,导致无限递归:每个 View 都推迟到其兄弟 View ,而兄弟 View 又推迟到初始 View :

- (UIView *) hitTestCGPoint)point withEventUIEvent *)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 ;
}

所以,我添加了一个“标记集”来跟踪已访问过哪个 View ,现在一切正常

- (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 ;
}



Best Answer-推荐答案


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

//编辑通过调用 UIView* view = [super hitTest:withEvent:]; 获得 hitTest View 。)

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

- (UIView *) hitTestCGPoint)point withEventUIEvent *)event {
    UIView * hit =  [super hitTest:point withEvent:event] ;

    if (hit == self) {
        return nil;
    }

    return hit ;
}

;)

关于ios - 重叠 UIView 上的 UITouch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9871372/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4