如何使触摸事件影响容器视图背后的视图

如何使触摸事件影响容器视图背后的视图

本文介绍了如何使触摸事件影响容器视图背后的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a container view completely covering another UIView. The container view has transparency along with a few other things (search bar, table view, etc). I want touch events to go through the container view and affect the view underneath when the event occurs in an area that is transparent.

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

I have been messing around with a subclass of a container view. I'm trying to get the pointInside: method to return YES or NO based on the above criteria (transparent container view). My problem is as far as I know I only have access to the container views subviews, not the view completely underneath the container view.

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

I have currently been using a very inefficient method of reading the touched pixels alpha. What would be the best way to go about doing this?

推荐答案

如果你只是想让触摸通过你的容器视图而仍然让它的子视图能够处理触摸,你可以继承 UIView 并覆盖 hitTest:withEvent:,如下所示:

If you just want touches to pass through your container view while still letting its subviews be able to handle touches, you can subclass UIView and override hitTest:withEvent: like this:

Swift:

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

Objective-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

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

Then have your container view be an instance of that class. Also, if you want your touches to pass through the above view controller's view, you will need to make that view controller's view also be an instance of that class.

这篇关于如何使触摸事件影响容器视图背后的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:51