In UIKit, how does an unhandled touch or a nil-target action climb the responder chain through UIResponder's next property?
answer
- each responder names its successor
- a root view hands off to its controller
- a controller hands off to its view's superview
- window, then application, then app delegate
- sendAction returns false when nobody answers
basics
~20 sUnhandled events go to each UIKit responder's next: a root view's controller, otherwise the superview; a controller's view's superview; then the window, UIApplication and the app delegate. A nil-target action starts at the first responder and climbs the same chain.
solid answer
~40 s`UIResponder` defines `next`, and UIKit's subclasses fill it in: a `UIView` returns the view controller that manages it, if it is that controller's root view, and otherwise its superview; a `UIViewController` returns its view's superview; a `UIWindow` returns the `UIApplication`, which returns its app delegate if that delegate is a `UIResponder` subclass. Touches climb this chain because the default `touchesBegan(_:with:)` family forwards to `next`, so an override that does not call `super` stops the climb. Actions use it too: a `UIControl` given a `nil` target, or `UIApplication`'s `sendAction(_:to:from:for:)` with `to: nil`, sends the selector to the first responder and lets it climb until some responder implements it. If none does, `sendAction` returns `false` and nothing runs.
code
swift · 26 linesimport UIKit
final class NoteEditorViewController: UIViewController {
@objc func toggleBold(_ sender: Any?) {
// Handles the action when no responder below this one did.
}
func makeBoldButton() -> UIButton {
let button = UIButton(type: .system)
button.setTitle("B", for: .normal)
// nil target: UIKit looks for an implementer of toggleBold(_:) in the responder chain.
button.addTarget(nil, action: #selector(toggleBold(_:)), for: .touchUpInside)
return button
}
}
extension UIResponder {
/// Prints the chain from this responder upwards, for debugging.
func printResponderChain() {
var responder: UIResponder? = self
while let current = responder {
print(type(of: current))
responder = current.next
}
}
}go deeper
Recall the order: view, its controller or superview, up to the window, the application and the app delegate.
Explain next for each class, that default touch methods forward to next, and that a nil-target action starts at the first responder and returns false if nobody handles it.
Use the chain to route toolbar and menu commands to whatever is focused, validate them with canPerformAction(_:withSender:), and debug misrouted events by printing the chain.
Decide where shared commands live, in focused responders or in controllers, so nil-target actions and menu validation behave predictably as screens are composed and reused.
## The chain is a linked list of responders Every object that can handle events in UIKit is a `UIResponder`: `UIApplication`, every `UIViewController`, and every `UIView`, which includes `UIWindow`. The **responder chain** is not stored anywhere as a list. Each responder answers one question, "who is next?", through its read-only `next` property, and UIKit follows those answers. `UIResponder` itself returns `nil`; the subclasses supply the links: | Responder | What `next` returns | |---|---| | `UIView` that is a view controller's root view | that `UIViewController` | | any other `UIView` | its superview | | `UIViewController` | its view's superview | | `UIWindow` | the `UIApplication` object | | `UIApplication` | normally `nil`, or the app delegate if it is a `UIResponder` subclass and has not already been asked | So from a button deep inside a note editor the chain runs: button, its container views, the editor's root view, the editor's view controller, the view that holds that root view (perhaps a navigation controller's view), and so on up to the window, the application and the app delegate. ## How unhandled touches climb Touches start at the view that hit testing found, not at the first responder. The default implementations of `touchesBegan(_:with:)`, `touchesMoved(_:with:)`, `touchesEnded(_:with:)` and `touchesCancelled(_:with:)` **forward the message to `next`**. That gives you two choices when you override them: - **Handle and stop**: implement the touch logic and do not call `super`. Apple's documentation adds that if you skip `super` in one of them you must override all four, even with empty bodies. - **Handle part and forward**: call `super` for the touches you do not want, and the superview or controller gets its chance. Most apps rarely write `touchesBegan(_:with:)` because gesture recognizers and controls do the work, but the forwarding rule explains why a container's touch handler never fires once a subview swallows the event. ## How nil-target actions climb Target-action is the other big user of the chain. A `UIControl` normally sends its action to an explicit target set with `addTarget(_:action:for:)`. Pass `nil` as the target and the header says the action "goes up the responder chain" instead. Underneath, `UIApplication`'s `sendAction(_:to:from:for:)` does the routing; with a `nil` target its documentation says the message goes to the **first responder** and climbs from there until it is handled. It returns `true` if a responder handled the action and `false` if none did; nothing crashes. This is what lets one formatting button work for whatever is focused: 1. A toolbar button is wired with `addTarget(nil, action: #selector(toggleBold(_:)), for: .touchUpInside)`. 2. The user taps it while a text view is first responder. 3. UIKit walks from the first responder upwards and calls `toggleBold(_:)` on the first responder that implements it, perhaps the editor's view controller. `UIResponderStandardEditActions` declares standard selectors such as `copy(_:)`, `paste(_:)` and `toggleBoldface(_:)` for exactly this style of dispatch, and `canPerformAction(_:withSender:)` and `target(forAction:withSender:)` let a responder say whether it will take an action: by default `target(forAction:withSender:)` returns `self` when `canPerformAction(_:withSender:)` says yes, and otherwise asks further up the chain. ## Touches and actions compared Both ride the same links, but they differ in three ways: - **Where they start.** A touch starts at the hit-test view under the finger; a `nil`-target action starts at the first responder. - **How they move.** A touch moves only when a touch method calls `super`; for an action, UIKit itself walks the chain looking for a responder that implements the selector. - **What happens at the end.** An unhandled touch is simply not handled; an unhandled action makes `sendAction(_:to:from:for:)` return `false`. ## Debugging the chain When an event lands somewhere unexpected, print the chain. Walk `next` from the view in question until it returns `nil` and log each type. Typical findings: - The action is implemented on a controller that is not an ancestor of the first responder, such as another tab's controller, so the walk never passes it. - An action method has a different selector from the one the control sends, so the walk passes it by. - A responder's `touchesBegan(_:with:)` override does not call `super`, so the climb stops there. ## Where the chain ends The app delegate is the last stop only when it subclasses `UIResponder`. For first-responder purposes, Apple's documentation says that since iOS 13 the root of the chain is the window scene's key window rather than the application's key window. After the last link, an unhandled action is dropped and `sendAction(_:to:from:for:)` reports `false`.
- Why does a nil-target action from a toolbar button never reach the view controller of another tab?The walk visits only `next` links from the first responder upwards, so it reaches ancestors: views, their controllers, the window and the application. Another tab's controller is a sibling, never an ancestor, so it is skipped and `sendAction(_:to:from:for:)` may return `false`. Move the handler to a responder on that path, or give the control an explicit target.
- How can a responder tell UIKit it will not handle a nil-target action even though it implements the method?Override `canPerformAction(_:withSender:)` and return `false` for that selector. The default `target(forAction:withSender:)` checks it and, on `false`, keeps asking further up the chain, so a responder higher up, or nobody, gets the action. This is also how the edit menu decides which commands to show.
The responder chain is like a support ticket that each desk either resolves or escalates to the one desk named above it; if the top desk cannot resolve it either, the ticket is closed unanswered rather than crashing the office.
- A view's next is always its superview, even for a view controller's root view.
- A nil-target action with no implementer crashes with an unrecognized selector.
- Touches start at the first responder and then move to the hit-test view.
- Gesture recognizers are responders and sit inside the responder chain.
- UIKit forwards a touch to next automatically after any touchesBegan(_:with:) override.