32
votes

In Messages.app you can dismiss the keyboard down by scrolling the list view. To be clear, it isn't simply responding to a scrollViewDidScroll event. The keyboard tracks with your finger as you swipe down. Any idea how this is done?

5

5 Answers

51
votes

Since iOS 7, you can use

scrollView.keyboardDismissMode = .Interactive

From the documentation:

UIScrollViewKeyboardDismissModeInteractive

The keyboard follows the dragging touch offscreen, and can be pulled upward again to cancel the dismiss.

13
votes

In the XCode, attributes inspector, the scrollView has a Keyboard attribute. It has 3 options.

  • Do not dismiss
  • Dismiss on drag
  • Dismiss interactive.

UIScrollView properties

6
votes

If you're using a tableView and Swift 3 or Swift 4, it works by using:

tableView.keyboardDismissMode = .onDrag
2
votes

Since iOS7, UIScroll​View and all classes that inherit from it (including UITableView) have a keyboard​Dismiss​Mode property. With Swift 5 and iOS 12, keyboard​Dismiss​Mode has the following declaration:

var keyboardDismissMode: UIScrollView.KeyboardDismissMode { get set }

The manner in which the keyboard is dismissed when a drag begins in the scroll view.

Note that UIScrollView.KeyboardDismissMode is an enum that has none, interactive and onDrag cases.


#1. Set keyboard​Dismiss​Mode programmatically

The code snippet below shows a possible implementation of keyboardDismissMode:

override func viewDidLoad() {
    super.viewDidLoad()

    // Dismiss keyboard when scrolling the tableView
    tableView.keyboardDismissMode = UIScrollView.KeyboardDismissMode.interactive

    /* ... */
}

#2. Set keyboard​Dismiss​Mode in storyboard

As an alternative to the programmatic approach above, you can set the keyboard​Dismiss​Mode value for your UIScrollView/UITableView in the storyboard.

  1. Select your UIScrollView / UITableView instance,
  2. Select the Attributes Inspector,
  3. Set the correct value for Keyboard.

enter image description here

-3
votes

Without tableview - yes it not a swipe but it doesn't the trick

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}