简体   繁体   中英

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!

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM