Dismiss keyboard with swipe gesture

2019-03-14 18:48发布

问题:

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?

回答1:

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.



回答2:

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

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



回答3:

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

tableView.keyboardDismissMode = .onDrag


回答4:

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)
}


回答5:

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

var keyboardDismissMode: UIScrollViewKeyboardDismissMode { get set }

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

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


#1. Set UIScrollViewKeyboardDismissMode programmatically

The code snippet below shows a possible implementation of keyboardDismissMode:

override func viewDidLoad() {
    super.viewDidLoad()

    // Dismiss keyboard when scrolling the tableView
    tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.interactive

    /* ... */
}

#2. Set UIScrollViewKeyboardDismissMode in storyboard

As an alternative to the programmatic approach above, you can set the UIScrollViewKeyboardDismissMode value for your UIScrollView in the storyboard.

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