UIView alpha 0 but still receive touch events?

2019-06-24 04:30发布

I am trying to hide a uiview but still have it receive touch events. I am setting the alpha to 0 like so:

mainView.alpha = 0.0

also I've tried setting this to true but it doesn't do anything

mainView.userInteractionEnabled = true

Trouble is it no longer receives touch events when I do this. How can I enable it to receive touch events but be effectively hidden?

标签: ios swift uiview
4条回答
乱世女痞
2楼-- · 2019-06-24 05:03

Hide all subviews of the view and set the backgroundColor to UIColor clearColor

查看更多
【Aperson】
3楼-- · 2019-06-24 05:06

Are you looking for a transparent view?

Just create a TransparantView sub class from UIView and copy below code. The view will be transparant, but still receive touches. You may need to change some code, because my code handles its subviews. The key is rewrite pointInside to meet your goals.

If you just want a transparent view, so other views under this transparent view can still get the touch events passed through the transparent view, you cannot add any subviews in transparentView.

The extended reading is to learn the responder chain.

@implementation TransparantView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    return self;
}

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    for (UIView *view in self.subviews) {
        if (!view.hidden && view.alpha > 0 && view.userInteractionEnabled && [view pointInside:[self convertPoint:point toView:view] withEvent:event])
            return YES;
    }
    return NO;
}
@end

UPDATE:

Seems iOS will not dispatch events to a view while its alpha is set to 0. However, the transparent view will have nothing on screen as if its alpha=0. I have updated the code to fix a bug

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    for (UIView *view in self.subviews) {
        if (!view.hidden && view.alpha > 0 && view.userInteractionEnabled && [view pointInside:[self convertPoint:point toView:view] withEvent:event])
            return YES;
    }
    if (!self.hidden && self.alpha >= 0.0 && self.userInteractionEnabled) {
        return YES;
    } else
        return NO;
}
@end
查看更多
Viruses.
4楼-- · 2019-06-24 05:14

Set your UIView's backgroundColor to UIColor.clear.

mainView.backgroundColor = .clear
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-06-24 05:14

There are two ways to handle this:

  1. The hard one - instead of setting alpha on the view, set it on all its subviews and make all the content in the view invisible (e.g. change background to clear color).

  2. The easy one - let another view handle the events. Just add another transparent view with the same position and size (which is easy using constraints) which will handle the events.

By the way, if you check the documentation for method hitTest:withEvent: which is used to handle touch events, it says that views with alpha lower than 0.01 won't receive touches.

查看更多
登录 后发表回答