skip to content

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%

answer

  1. recognizers see touches before the view
  2. a tap is a discrete recognizer
  3. touchesCancelled reaches the table view
  4. cancelsTouchesInView defaults to true
  5. delaysTouchesEnded defaults to true

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.

solid answer

~40 s

A gesture recognizer handles touches hit-tested to its view **and every subview**, and the window delivers them to the recognizer before the view. A tap recognizer on the controller's root view therefore watches every touch on the table. A tap is discrete: it moves from `.possible` to `.recognized` or `.failed`. Because `delaysTouchesEnded` defaults to `true`, the table view does not get `touchesEnded(_:with:)` while the tap might still succeed; when the tap is recognized, `cancelsTouchesInView`, also `true` by default, sends `touchesCancelled(_:with:)` instead. The table view loses the touch and selects nothing. Fixes: set `cancelsTouchesInView = false` so both happen, return `false` from `gestureRecognizer(_:shouldReceive:)` for touches you want left alone, or drop the recognizer and set the table view's `keyboardDismissMode`.

code

swift · 25 lines
swift
import UIKit

final class NotesListViewController: UIViewController, UIGestureRecognizerDelegate {
    let tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        // Default is true: a recognized tap cancels the touches the table view was tracking.
        tap.cancelsTouchesInView = false
        tap.delegate = self
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                           shouldReceive touch: UITouch) -> Bool {
        // Let buttons and other controls handle their own touches.
        !(touch.view is UIControl)
    }
}

go deeper

for a junior

Know that a gesture recognizer on a parent view also watches touches on its subviews, and that cancelsTouchesInView is true by default.

for a middle

Explain the sequence: the recognizer sees touches first, touchesEnded is withheld, and recognition turns it into touchesCancelled, so the row never completes its selection.

for a senior

Pick the fix by intent: cancelsTouchesInView = false when both should act, gestureRecognizer(_:shouldReceive:) when some touches should be ignored, keyboardDismissMode for scrolling lists.

for a principal

Agree on one dismissal pattern for forms and lists so screens stop adding root-view tap recognizers that quietly break selection in reused components.

## The symptom A notes list has a search field at the top. To dismiss the keyboard, someone adds a `UITapGestureRecognizer` to the view controller's root view whose action calls `view.endEditing(true)`. The keyboard now goes away, but tapping a note no longer opens it: `tableView(_:didSelectRowAt:)` is never called. Nothing is wrong with the table view. The tap recognizer took the touches away from it. ## How a recognizer gets the touches first Three documented rules combine here: - **Scope.** A gesture recognizer operates on touches hit-tested to its view **and all of that view's subviews**. A recognizer on the root view sees touches on every cell. - **Order.** The window delivers each touch to the relevant gesture recognizers before it delivers it to the hit-test view. - **States.** A tap is a **discrete** recognizer. It starts in `.possible` and moves to `.recognized` (the same constant as `.ended`), which sends its action, or to `.failed`. A continuous recognizer such as a pan instead goes `.possible`, `.began`, `.changed` and then `.ended` or `.cancelled`. ## Why the row loses its touch Two properties of `UIGestureRecognizer` decide what the hit-test view sees while recognition is undecided and after it succeeds: | Property | Default | Effect | |---|---|---| | `delaysTouchesBegan` | `false` | the view gets began-phase touches in parallel with the recognizer | | `delaysTouchesEnded` | `true` | ended-phase touches are withheld from the view until the recognizer fails | | `cancelsTouchesInView` | `true` | once the gesture is recognized, the view gets `touchesCancelled(_:with:)` for its touches | A single short tap on a row is exactly what the tap recognizer is looking for, so it recognizes. The end of the touch was withheld while the tap was still possible, and recognition replaced it with a cancellation. Row selection needs the touch to end normally; a cancelled touch selects nothing. Some controls survive the same recognizer: `UIView` declares `gestureRecognizerShouldBegin(_:)` so that a subclass can veto a recognizer that would otherwise start on it (the header's example is `UISlider` refusing swipes along its track). Do not rely on that for your own rows; fix the recognizer. ## Three fixes, and when each fits 1. **Stop cancelling.** Set `cancelsTouchesInView = false`. The recognizer still fires its action, and the table view also gets the full touch sequence, so a tap on a row both dismisses the keyboard and selects the note. This is the smallest change. 2. **Filter what the recognizer receives.** Become its delegate and return `false` from `gestureRecognizer(_:shouldReceive:)` for touches whose `view` is a `UIControl` or lies inside the table view. UIKit calls it before the recognizer's own `touchesBegan(_:with:)`, so filtered touches never reach the recognizer at all. 3. **Remove the recognizer.** `UITableView` is a `UIScrollView`, and its `keyboardDismissMode` can be `.onDrag` or `.interactive`. Scrolling the list dismisses the keyboard and taps are left alone. Many teams prefer this for lists, and add a tap recognizer only on non-scrolling forms. ## Which fix to choose The three fixes are not interchangeable, so pick by what the screen should do: - If a tap on a row should **both** dismiss the keyboard and open the note, `cancelsTouchesInView = false` gives exactly that. - If taps on rows and buttons should **only** do their own thing, and background taps should dismiss the keyboard, filter with `gestureRecognizer(_:shouldReceive:)`. - If the screen is a scrolling list, `keyboardDismissMode` removes the recognizer and the conflict along with it. ## Related properties worth knowing - `isEnabled = false` stops a recognizer from receiving touches, and switching it off mid-gesture cancels the gesture. - `require(toFail:)` makes one recognizer wait for another to fail, the classic case being a single tap that must wait for a double tap. - `delaysTouchesBegan = true` is the opposite trade: the view sees nothing until the recognizer fails, which makes rows feel sluggish to respond. ## How to confirm the diagnosis Set breakpoints in the recognizer's action method and in `tableView(_:didSelectRowAt:)`, then tap a row: only the action fires. Set `cancelsTouchesInView` to `false` and tap again: the touch now ends normally, and the selection callback runs alongside the keyboard dismissal. If the selection still never arrives, look for a second recognizer or a delegate that refuses the touch. Setting the recognizer's `name` property makes it easier to spot when you inspect the gesture recognizers attached to a view while debugging.

  • What changes if you set delaysTouchesBegan to true on the same tap recognizer?
    The table view stops seeing began-phase touches until the recognizer fails, so a row cannot react to the touch while the tap is still possible. If the tap is recognized, those began touches are discarded entirely. It makes the list feel slower and fixes nothing; the default `false` is right here.
  • When is gestureRecognizer(_:shouldReceive:) a better fix than cancelsTouchesInView = false?
    When the recognizer's action should not run at all for some touches, for example a tap on a button or a row should not also trigger the background behaviour. Returning `false` keeps those touches away from the recognizer before it starts, whereas `cancelsTouchesInView = false` lets both the recognizer and the view act on the same tap.

  • A gesture recognizer only sees touches on the exact view it is attached to.
  • A tap recognizer on the root view never affects a table view's selection.
  • cancelsTouchesInView defaults to false, so cancelling must be opted into.
  • The table view receives touchesEnded(_:with:) before the recognizer decides.
  • Gesture recognizers sit in the responder chain after the hit-test view.