skip to content

Responder Chain & Events

A touch is routed by hit testing to a view, then climbs the responder chain if nothing handles it. Interviewers check you can explain why a tap never reached a button or the keyboard will not dismiss.

on this pageshow

explore

questions

6

In a UIKit note editor, how do becomeFirstResponder(), resignFirstResponder() and endEditing(_:) decide whether the keyboard is on screen?

level: juniorimportance: must knowfreq 70%

answer

  1. one focus holder per window
  2. the keyboard is an input view
  3. canBecomeFirstResponder is false by default
  4. the view must already be in a window
  5. endEditing(true) overrides a delegate veto

basics

~20 s

UIKit shows the keyboard as the first responder's input view: becomeFirstResponder() on a text field or text view brings it up, resignFirstResponder() hides it, and endEditing(_:) resigns whichever view in a subtree is first responder.

solid answer

~40 s

In UIKit the keyboard belongs to whichever responder is first responder in the key window: when a `UITextField` or `UITextView` takes that role, UIKit shows its input view, the system keyboard. `becomeFirstResponder()` asks for the role and returns a `Bool`, because the current first responder may refuse to resign and because `canBecomeFirstResponder` is `false` on a plain `UIView` unless a subclass overrides it. Call it only once the view is in a window, for example in `viewDidAppear(_:)`. `resignFirstResponder()` gives the role up and the keyboard goes away; a text field's delegate typically calls it from `textFieldShouldReturn(_:)`. When you hold no reference to the field, `view.endEditing(true)` resigns whichever view under `view` is first responder, and `true` forces it even when the field's delegate returns `false` from `textFieldShouldEndEditing(_:)`.

code

swift · 26 lines
swift
import UIKit

final class NoteEditorViewController: UIViewController, UITextFieldDelegate {
    let titleField = UITextField()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // The field is in a window now, so it can take focus and show the keyboard.
        titleField.becomeFirstResponder()
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

    @objc func doneTapped() {
        // Resigns whichever text field or text view under this view is first responder.
        view.endEditing(true)
    }
}

final class CanvasView: UIView {
    // A plain UIView returns false here, so becomeFirstResponder() would fail.
    override var canBecomeFirstResponder: Bool { true }
}

go deeper

for a junior

Know that the keyboard appears because a text field or text view became first responder, and that resignFirstResponder() or endEditing(true) on the root view makes it go away.

for a middle

Explain why becomeFirstResponder() returns a Bool: the current first responder may refuse, canBecomeFirstResponder is false by default, and the view must already be in a window.

for a senior

Diagnose a keyboard that will not dismiss: endEditing on a view that does not contain the field, a delegate refusing to end editing, or code that re-focuses the field on the next layout pass.

for a principal

Set a team convention for dismissal, such as keyboardDismissMode on scrolling forms and endEditing on the root view, so screens do not each add their own background tap recognizer.

## What first responder means UIKit routes several kinds of input to one object per window, the **first responder**. Touches go to the view that hit testing finds, but key presses from a hardware keyboard go to the first responder, and actions sent to a `nil` target start there. A `UIResponder` subclass that becomes first responder also gets its **input view** displayed: for a `UITextField` or `UITextView`, that input view is the system keyboard. That is the whole model behind "the keyboard is showing": the keyboard is on screen because some text view or text field is first responder, and it leaves when that object stops being first responder. So you never show or hide the keyboard directly. You move first-responder status, and the keyboard follows. ## Taking focus with becomeFirstResponder() `becomeFirstResponder()` asks UIKit to make the receiver the first responder of its window, and it returns a `Bool` because the request can fail: - UIKit first asks the **current** first responder to resign. It may refuse, and then nothing changes. - UIKit then checks the receiver's `canBecomeFirstResponder`, which is **`false` by default** on `UIResponder`. Text fields and text views return `true`; a custom canvas view must override the property before it can take focus, for example to receive key commands. - Apple's documentation says to call it **only on views in the active view hierarchy**: check that the view's `window` is not `nil`. In `viewDidLoad()` the view has no window yet, so focusing a field there is unreliable; `viewDidAppear(_:)` is a safe place. - The software keyboard appears only when the responder's window is the **key window**, and since iOS 13 the root of the chain is the window scene's key window. ## Giving it up: resignFirstResponder() and endEditing(_:) | API | Called on | What it does | |---|---|---| | `resignFirstResponder()` | the current first responder | gives up the role; the keyboard goes away if it succeeds | | `endEditing(_:)` | any `UIView`, usually the root view | finds the first responder in that view's subtree and makes it resign | | `sendAction(_:to:from:for:)` with a `nil` target | `UIApplication.shared` | delivers a selector such as `resignFirstResponder` to the first responder, wherever it lives | `resignFirstResponder()` returns `true` by default, but a responder can override it, or `canResignFirstResponder`, to refuse. A text field also consults its delegate: `textFieldShouldEndEditing(_:)` returning `false` keeps the editing session alive. `endEditing(false)` respects that answer; `endEditing(true)` **forces** the resignation, and the header notes that `textFieldDidEndEditing(_:)` can then run even though the delegate said no. The usual pattern in a note editor: the title field resigns from `textFieldShouldReturn(_:)`, and a Done button or a tap on the background calls `view.endEditing(true)` on the controller's root view. ## Why the keyboard will not go away When the keyboard stays up, one of these is usually true: 1. **`endEditing(_:)` was called on the wrong view.** It searches only that view's subtree. A field inside a presented controller or another window is not under your root view. 2. **`resignFirstResponder()` was sent to an object that is not first responder**, such as the view controller or its root view. It returns without effect. 3. **A delegate or override refuses.** `textFieldShouldEndEditing(_:)` returns `false`, or a custom responder returns `false` from `resignFirstResponder()`. 4. **Something takes focus straight back.** A `becomeFirstResponder()` call in `viewWillAppear(_:)`, a layout pass or a reload re-focuses the field after you dismissed it. When you do not know which object holds focus, send the action to the chain instead: `UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)`. With a `nil` target, `UIApplication` sends the message to the first responder, and the call returns `false` if nothing handled it. ## Letting a scroll view dismiss it For a long note in a `UIScrollView`, a `UITableView` or a `UITextView` (all scroll views), `keyboardDismissMode` handles the gesture for you. The default is `.none`; `.onDrag` dismisses the keyboard when a drag begins, and `.interactive` lets the keyboard follow the finger off screen and be pulled back up to cancel. This often replaces a hand-made tap recognizer, which has its own side effects on touch delivery. ## A custom responder A drawing canvas that wants key commands, a custom input view or the edit menu overrides `canBecomeFirstResponder` to return `true` and calls `becomeFirstResponder()` once it is on screen. If it overrides `becomeFirstResponder()` or `resignFirstResponder()` to update its own state, such as a selection highlight, it must call `super`.

  • Why can becomeFirstResponder() return false when called from viewDidLoad()?
    In `viewDidLoad()` the view is not yet in a window, and Apple's documentation says to call `becomeFirstResponder()` only on views in the active hierarchy, which you check with `window`. The request can also fail because the current first responder refuses to resign. Move the call to `viewDidAppear(_:)` and read the returned `Bool` if focus matters.
  • How do you dismiss the keyboard when you do not know which text field or text view has focus?
    Call `endEditing(true)` on a view that contains every candidate, usually the controller's root view, or send `resignFirstResponder` to the chain with `UIApplication.shared.sendAction(_:to:from:for:)` and a `nil` target. The second form reaches the first responder even when it sits outside the view you hold, and returns `false` if nothing handled it.
  • What does UIScrollView's keyboardDismissMode add, and what is its default?
    It lets a drag in the scroll view dismiss the keyboard without a gesture recognizer of your own. The default is `.none`. `.onDrag` dismisses when a drag begins, and `.interactive` makes the keyboard track the finger off screen and lets the user pull it back up to cancel. Table views and text views inherit it because they are scroll views.

First responder works like a single talking stick in a meeting: only the holder speaks, you ask the current holder to pass it before you can take it, and the holder is allowed to refuse.

  • Calling becomeFirstResponder() in viewDidLoad() reliably shows the keyboard.
  • Any UIView can become first responder without overriding anything.
  • endEditing(_:) hides the keyboard wherever the focused field lives in the app.
  • Calling resignFirstResponder() on the view controller dismisses its fields' keyboard.
  • A window can hold several first responders, one per visible text field.
open as a page

In UIKit, how does hitTest(_:with:) choose the view that receives a touch, and which views does it pass over?

level: middleimportance: must knowfreq 72%

basics

~20 s

UIKit's hitTest(_:with:) walks down from the window, keeping only branches whose point(inside:with:) contains the touch, and returns the deepest frontmost view; hidden views, views with interaction disabled and views with alpha below 0.01 are skipped.

open as a page

In a UIKit notes list, a UITapGestureRecognizer added to dismiss the keyboard stops table rows from being selected; why, and what fixes it?

level: middleimportance: must knowfreq 64%

basics

~20 s

A tap recognizer on the root view sees each row's touches first; when it recognizes, cancelsTouchesInView (true by default) cancels them, so the table view never sees the touch end. Set it to false, filter touches in the delegate, or use keyboardDismissMode.

open as a page

In a UIKit note app, a horizontal pan on a card inside a vertical UIScrollView either blocks scrolling or never starts; how do you settle the conflict between the two recognizers?

level: seniorimportance: must knowfreq 60%

basics

~20 s

The card's pan and the scroll view's panGestureRecognizer both see the touch, and by default one recognizing blocks the other. Begin the card's pan only for mostly horizontal drags in gestureRecognizerShouldBegin(_:), and make the scroll view's pan require(toFail:) it.

open as a page

In UIKit, how does an unhandled touch or a nil-target action climb the responder chain through UIResponder's next property?

level: middleimportance: should knowfreq 58%

basics

~20 s

Unhandled 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.

open as a page

In a UIKit note app, a floating toolbar's small buttons are hard to hit and its pop-out colour palette ignores taps; how do you fix both with point(inside:with:)?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Hit testing searches a subview only if its superview's point(inside:with:) contains the touch, so a palette outside the toolbar's bounds is unreachable. Override the toolbar's point(inside:with:) to claim its subviews' frames, and the buttons' to test an outset bounds.

open as a page