How to Make Touch Events Affect View's Behind a Container View?

后端 未结 1 716
失恋的感觉
失恋的感觉 2021-01-05 06:17

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 eve

相关标签:
1条回答
  • 2021-01-05 06:38

    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.

    0 讨论(0)
提交回复
热议问题