For the More Curious: The Responder Chain

In Chapter 14, we talked briefly about the first responder. A UIResponder can be a first responder and receive touch events. UIView is one example of a UIResponder subclass, but there are many others, including UIViewController, UIApplication, and UIWindow. You are probably thinking, But you can’t touch a UIViewController. It’s not an onscreen object. You are right – you cannot send a touch event directly to a UIViewController, but view controllers can receive events through the responder chain.

Every UIResponder can reference another UIResponder through its next property, and together these objects make up the responder chain (Figure 18.8). A touch event starts at the view that was touched. The next responder of a view is typically its UIViewController (if it has one) or its superview (if it does not). The next responder of a view controller is typically its view’s superview. The top-most superview is the window. The window’s next responder is the singleton instance of UIApplication.

Figure 18.8  Responder chain

Illustration shows a responder chain.

How does a UIResponder not handle an event? It calls the same method on its next responder. That is what the default implementation of methods like touchesBegan(_:with:) does. So if a method is not overridden, its next responder will attempt to handle the touch event. If the application (the last object in the responder chain) does not handle the event, then it is discarded.

You can explicitly call a method on a next responder, too. Let’s say there is a view that tracks touches, but if a double-tap occurs, its next responder should handle it. The code would look like this:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    if touch.tapCount == 2 {
        next?.touchesBegan(touches, with: event)
    } else {
        // Go on to handle touches that are not double-taps
    }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset