如何覆盖hitTest以允许我的子视图接收触摸事件?

时间:2014-08-12 03:55:58

标签: ios objective-c hittest

我有一个包含另一个视图的UIView,它自己包含一个UIButton。问题是MENUVIEW非常窄,所以我的DROPDOWN延伸到它上面,当它发生时,用户点击(K)没有任何反应。我知道我必须覆盖HitTest:和pointInside:但我不确定在哪个视图中以及如何操作?

我是否覆盖A,B或K中的hitTest?并指向内部A,B或K?

示例:

(A) is MENUVIEW, the parent of all views
(B) is DROPDOWN, a subview of MENUVIEW
(K) is UIBUTTON, a subview of DROPDOWN

图:

    +---------------+
    |A              |         
    |               |               
    |               |         
    |               |         
    |+--------------|----------+
    ||B             |  +K---+  |
    ||              |  +----+  |
    |+--------------|----------+
    +---------------+

更新:

这是我放置的代码,但它不起作用。使用下面的代码,我点击B然后B将打开并显示K,但是K仍然无法点击。内部点是否被调用(A)?

    #pragma mark - Clickable Area()
    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
    {
        CGFloat radius = 200.0;
        CGRect frame = CGRectMake(self.dropDownMenu.frame.origin.x, self.dropDownMenu.frame.origin.y + 50,
                                  200,
                                  174); <-- this B's frame area minus the part of B inside A (i.e. just K and the part of B outside A)

        if (CGRectContainsPoint(frame, point)) {
            return self.dropDownMenu;
        } else {
            return [super hitTest:point withEvent:event];
        }
        return nil;
    }

    - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
    {
        if (CGRectContainsPoint(self.bounds, point)) {
            return YES;
        }
        return NO;
    }

    @end

1 个答案:

答案 0 :(得分:0)

你应该做一个足够大的父视图。并覆盖d的pointInside和hittest 当该点不在a | b | c区域时,返回nil让下面的视图响应该事件。(return nil表示userinteractionenabled = NO)

- (UIView *) hitTest:(CGPoint)point withEvent:(UIEvent *)event {
1.convert b's frame to the view D
if (point inside B's convertedFrame) {
    return B;
}
xxxxx {
    return A
}
XXXXX {
    return C;
}
return nil;
}

+-----------------------------+
+---------------+           D |
|A              |             |
|               |             |  
|               |             |
|               |             |
|+--------------|----------+  |
||B             |  +K---+  |  |
||              |  +----+  |  |
|+--------------|----------+  |
+---------------+             |
+-----------------------------+

如果b响应事件,则k甚至可以响应不在a内的k。