iOS Responder Chain

Bored 🥑
3 min readAug 22, 2017

--

This account is no longer in use. Please checkout my latest articles in iOS Interview Preparation Complete Guide.

Apps receive and handle events using responder objects. A responder object is any instance of the UIResponder class, and common subclasses include UIView, UIViewController, and UIApplication. UIKit manages most responder-related behavior automatically, including how events are delivered from one responder to the next.

For every event, UIKit designates a first responder and sends the event to that object first. The first responder varies based on the type of event.

UIKit uses view-based hit testing to determine where touch events occur. Specifically, UIKit compares the touch location to the bounds of view objects in the view hierarchy. The hitTest:withEvent: method of UIViewwalks the view hierarchy, looking for the deepest subview that contains the specified touch. That view becomes the first responder for the touch event.

If a touch location is outside of a view’s bounds, the hitTest:withEvent: method ignores that view and all of its subviews. As a result, when a view’s clipsToBounds property is NO, subviews outside of that view’s bounds are not returned even if they happen to contain the touch.

  • If the view is the root view of a view controller, the next responder is the view controller.
  • If the view is not the root view of a view controller, the next responder is the view’s superview.
  • If the view controller’s view is the root view of a window, the next responder is the window object.
  • If the view controller was presented by another view controller, the next responder is the presenting view controller.
  • UIWindow. The window’s next responder is the application object.
  • UIApplication. The app object’s next responder is the app delegate, but only if the app delegate is an instance of UIResponder and is not a view, view controller, or the app object itself.

Event Queue

Applications in cocoa and cocoa touch have an event queue associated to them, this event queue will be filled with events from multiple sources. In order to handle the stream of event, each application maintain an event run loop that accepts and dispatches events in a first in first out order.

When an application is launched the call to UIApplicationMain will create a UIApplication singleton object, this object will be responsible for handling and dispatching the events the system sends to the app events queue.

Each of these events will be handled and processed by the application singleton before being dispatched to the appropriate receivers which follows the responder chain.

--

--