Thursday, Oct 29, 2009 Intercepting multi-touch event in UIView
Intercepting events from being delivered to subviews of a UIView appears to be a straightforward problem. Well, at least, the solution should be straightforward, right? Tape into the event delivery queue and intercept events that we don’t want to be delivered to subviews.
This is actually not that straightforward actually.
Apple provides detail documentation on how events are handled and processed in iPhone OS.
Quotes from the documentation:
- “Restricting event delivery to subviews. A custom UIView class can override hitTest:withEvent: to restrict the delivery of multi-touch events to its subviews. See “Hit-Testing” for a discussion of this technique.” – from Regulating Event Delivery
- “Override sendEvent: in a custom subclass of UIWindow, analyze touches, and forward them to the appropriate responders. In your implementation you should always invoke the superclass implementation of sendEvent:.” – from Forwarding Touch Events
In my particular case, there’s a UIView which contains a bunch of UIButton views inside it. The UIView should intercept all events and forward only single touch event to subviews.
In the code, I subclass the UIView and override the hitTest method. However, I found that the “event” object passed by hitTest method contains no touch object at all. [event allTouches] returns an empty set. Google around and found that I am not alone to this problem
I did some more research and found a few forum discussions in Apple’s official developer forum where some Apple engineers explain why it is not simply overriding hitTest nor other event handling methods in UIResponder class (touchesBegan, touchesMoved, touchesEnded, touchesCancelled).
In one sentence, it is not possible to forward touches to UIKit object by overriding UIResponder methods. For detail explanation, please read through these links:
The solution? As suggested in by Ryan (first link in above list), override sendEvent: method in UIWindow. Check out his post for detail explanation to the solution.
Someone, in the comment section, pointed another page with sample code to the problem.
I’ll post sample code of my solution in a bit.
SEO is actually very simple Replace your Macbook / Macbook Pro superdrive with hard disk