[英]How to Make Touch Events Affect View's Behind a Container View?
I have a container view completely covering another UIView. 我有一个容器视图完全覆盖另一个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. 我希望触摸事件通过容器视图,并在事件发生在透明区域时影响下面的视图。
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). 我正在尝试使用pointInside:方法根据上述标准(透明容器视图)返回YES或NO。 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. 我的问题是据我所知,我只能访问容器视图子视图,而不是容器视图下面的视图。
I have currently been using a very inefficient method of reading the touched pixels alpha. 我目前一直在使用一种非常低效的方法来读取触摸的像素alpha。 What would be the best way to go about doing this? 这样做最好的方法是什么?
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: 如果你只是希望触摸通过你的容器视图,同时仍然让它的子视图能够处理触摸,你可以UIView
并覆盖hitTest:withEvent:
像这样:
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: 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. 此外,如果您希望触摸通过上述视图控制器的视图,则需要使该视图控制器的视图也是该类的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.