Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView alpha 0 but still receive touch events?

Tags:

ios

swift

uiview

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?

like image 342
Tyler Avatar asked May 15 '15 22:05

Tyler


2 Answers

Set your UIView's backgroundColor to UIColor.clear.

mainView.backgroundColor = .clear
like image 195
Daniel Storm Avatar answered Nov 16 '22 04:11

Daniel Storm


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.

like image 45
Sulthan Avatar answered Nov 16 '22 03:11

Sulthan