How to pass the touch event to superview when userInteractionEnabled = YES?

后端 未结 6 1097
青春惊慌失措
青春惊慌失措 2020-12-17 14:24

I have the following setup.

+- XXXCustomControl : UIControl -------+
| A                                    |
|   +- ContentView -------------------+|
|   |         


        
相关标签:
6条回答
  • 2020-12-17 14:40

    Use this in super view, without changing subviews code (since subviews may be introduced from other frameworks or pods):

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
    {
        UIView *view = [super hitTest:point withEvent:event];
        if ([view isDescendantOfView:self])
        {
            NSLog(@"touched inside");
        }
        return view;
    }
    
    0 讨论(0)
  • 2020-12-17 14:48

    You can use another UIView to "hide" the subview.

    *Details : This UIView is the subview's sibling . it has the same size and position of your subview with background color of clear color.

    *Explain: The new UIView will take the touch, and automatically pass it to the superview.

    This way doesn't need to subclass your subview - it's a storyboard solution.
    Please try this. Have fun!

    0 讨论(0)
  • 2020-12-17 14:48

    - Swift

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if <#condition#> { return true }
        else { return false }
    }
    
    0 讨论(0)
  • 2020-12-17 14:54

    You could try overriding the pointInside:withEvent: method in your inner view. This will allow you to return NO when you want to forward touches to the superview:

    -(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
    {
        if( /* You have content, and you want to receive touches */){
            return YES;
        }else{
            return NO;
        }
    }
    
    0 讨论(0)
  • 2020-12-17 14:57

    You can subclass your subview, and implement

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        if (!touchedContent) {
            [[self nextResponder] touchesBegan:touches withEvent:event];
        } else {
            [super touchesBegan:touches withEvent:event];
        }
    }
    
    0 讨论(0)
  • 2020-12-17 15:06

    If you want to handle the event from superview(XXXCustomControl in your case) instead of inner view(ContentView in your case), you can write the following swift code in your superview:

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let view = super.hitTest(point, with: event) else { return nil }
        if view.isDescendant(of: self) {
            // your custom logic
        }
        return view
    }
    
    0 讨论(0)
提交回复
热议问题