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?
Hide all subviews of the view and set the backgroundColor to UIColor clearColor
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.
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
Set your
UIView
'sbackgroundColor
toUIColor.clear
.There are two ways to handle this:
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).
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 than0.01
won't receive touches.