ishahak
ishahak

Reputation: 6795

UIButton on top of view with userInteractionEnabled=NO

I'm creating a transparent layer on top of keyWindow

UIWindow *window = [[UIApplication sharedApplication] keyWindow];
_topLayer = [[UIView alloc] initWithFrame:window.frame];
_topLayer.backgroundColor = [UIColor clearColor];
_topLayer.userInteractionEnabled = NO;
[window addSubview:_topLayer];

I'm adding subview that I want to appear on top of everything. I used

userInteractionEnabled = NO

so that layer is not blocking taps to the underneath staff.

I was trying to add a UIButton on top of that layer, but it is not responding to taps, due to the above userInteractionEnabled = NO

How can I allow the button to be responsive, while leaving the full background as transparent?

Thank you in advance!

Upvotes: 0

Views: 303

Answers (2)

ishahak
ishahak

Reputation: 6795

The answer of @anhtu is a real complication to what I was trying to achieve. The correct way is to set the button as a sibling of of the transparent view, instead of adding it as a child view.

See an expansion of this here: https://stackoverflow.com/a/35592676/913347

Upvotes: 0

tuledev
tuledev

Reputation: 10327

You can do this: subclass the UIView with userInteractionEnabled=YES then use this snippet:

-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    id hitView = [super hitTest:point withEvent:event];
    if (hitView == self) return nil; // <--- pass-through if touch on UIView
    else return hitView; // touch on children
}

Upvotes: 1

Related Questions