问题
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.
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.
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?
回答1:
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.
来源:https://stackoverflow.com/questions/25238722/how-to-make-touch-events-affect-views-behind-a-container-view