UIView — “user interaction enabled” false on parent but true on child?

前端 未结 6 572
北海茫月
北海茫月 2020-12-08 13:02

It appears that userInteractionEnabled=NO on a parent view will prevent user interaction on all subviews. Is this correct? Is there any way around this?

6条回答
  •  北海茫月
    2020-12-08 13:38

    You can subclass UIView and override hitTest:withEvent: in a way to pass touch events to a view that you specify (_backView):

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        UIView *view = [super hitTest:point withEvent:event];
    
        if (view == self) {
            view = _backView;
        }
    
        return view;
    }
    

    If the touch event was to be handled by this view it would be passed to "_backView" (that can be an IBOutlet so that it can be set using interface builder) ; and if it was to be handled by any child view just return that child (the result of [super hitTest:point withEvent:event];)

    This solution is fine as long as you know what view you need to pass the events to; besides don't know if it has problems since we are returning a view (_backView) that is not a subview of the current UIView !! but it worked fine in my case.

    A better solution might be the one mentioned in Disable touches on UIView background so that buttons on lower views are clickable There its mentioned to use -pointInside:withEvent: ; compared to previous solution its better in the way that you don't need to specify a '_backView' to receive the events (the event is simply passed to the next view in chain)! drawback might be that we need to perform -pointInside:withEvent: on all subviews (might be of negligible overhead though)

提交回复
热议问题