Hit Me Views, One More Time

James Pang
Tech with Pangers
Published in
2 min readSep 11, 2016

So in a side project that I am working on, I have a view that lives outside of the bounds of its parent’s bounds. Due to this, the view does not receive any touch events. What gives?

Well it turns out that this is the default behaviour of the touch system of UIKit. Stated again, when a view lives outside the bounds of its parent’s view, any sort of touch interaction does NOT get propagated to the view. This is because of how the hit-testing process (the way in determining which view a ‘touch’ event belongs to) works in UIKit.

When a touch occurs (whether it be from a tap, drag, zoom in etc.), the root view of the ENTIRE view hierarchy takes control of the process. What happens at a high level is this:

  1. The root view (usually the Application’s window) sends the touch events to it’s NEWEST subview (it checks the subviews property of the view).
  2. For each subview, a check is made (pointInside:withEvent:) whether the touch is in it’s parent view’s bounds. If the touch point is OUTSIDE, the hit-test method of the view (hitTest:withEvent:) will return nil.
  3. If the touch point is INSIDE the parent’s bounds, the hit-test method will call THAT subview’s hit-test method until the very final view is returned.

If you would like to receive touch events with a view that is outside the parent’s bounds, you must override the parent view’s hit-test method like the following:

In the context of an iOS App, my outOfBoundsView was a subview of a View Controller’s view. So what I did to get this working was:

  1. Create a UIView subclass
  2. Go to storyboard and set the Custom Class of theView Controller’s view to the UIView subclass
  3. Create an IBOutlet of the outOfBoundsView in the UIView subclass
  4. Implement the method in the above gist

Bingo.

--

--