8

我有一个完全覆盖另一个 UIView 的容器视图。容器视图与其他一些东西(搜索栏、表格视图等)一起具有透明度。我希望触摸事件通过容器视图并在事件发生在透明区域时影响下面的视图。

我一直在搞乱容器视图的子类。我试图让 pointInside: 方法根据上述标准(透明容器视图)返回 YES 或 NO。我的问题是据我所知,我只能访问容器视图子视图,而不是完全位于容器视图下方的视图。

我目前一直在使用一种非常低效的方法来读取触摸像素 alpha。这样做的最佳方法是什么?

4

1 回答 1

10

如果您只想让触摸通过您的容器视图,同时仍然让其子视图能够处理触摸,您可以像这样子类化UIView和覆盖hitTest:withEvent:

迅速:

class PassthroughView: UIView {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        // Get the hit view we would normally get with a standard UIView
        let hitView = super.hitTest(point, with: event)

        // If the hit view was ourself (meaning no subview was touched),
        // return nil instead. Otherwise, return hitView, which must be a subview.
        return hitView == self ? nil : hitView
    }
}

目标-C:

@interface PassthroughView : UIView
@end

@implementation PassthroughView

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    // Get the hit view we would normally get with a standard UIView
    UIView *hitView = [super hitTest:point withEvent:event];

    // If the hit view was ourself (meaning no subview was touched),
    // return nil instead. Otherwise, return hitView, which must be a subview.
    return hitView == self ? nil : hitView;
}

@end

然后让您的容器视图成为该类的实例。此外,如果您希望您的触摸通过上述视图控制器的视图,您需要使该视图控制器的视图也成为该类的实例。

于 2014-08-11T08:45:22.123 回答