Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide keyboard when scroll UITableView

Here is the cleanest way to achieve this in iOS 7.0 and above:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

Or to dismiss interactively when touching:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

Or in Swift:

tableView.keyboardDismissMode = .onDrag

To dismiss interactively:

tableView.keyboardDismissMode = .interactive

Not sure why you need to subclass UITableView for this.

In the view controller that contains the plain UITableView, try adding this:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [searchBar resignFirstResponder];
}

You can do this right in Interface Builder. Select your UITableView and open the Attributes Inspector. In the Scroll View section set the Keyboard field to Dismiss on Drag.

enter image description here


Just to add an update to the answers above. The below worked for me in Swift 1.2

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

or

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive

With Swift 5

To hide the keyboard when scrolling the TableView and stop editing properly, we still need to combine two types of answers:

  1. Set the keyboard dismiss mode in IB (as Kyle explained) or in ViewDidLoad() code (as Pei explained) for instance:
tableView.keyboardDismissMode = .onDrag
  1. Force the current textfield to resign as first responder (as in Vasily's answer). We just need to add the following to our UITableViewController class
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !tableView.isDecelerating {
            view.endEditing(true)
        }
    }

Working solution without writing single line of code in your Controller:

As your question is to handle the hide keyboard with one condition only (on scroll). But here I am recommending one solution to handle textfield and keyboard together which works like charm for UIViewController, UITableView and UIScrollView. The interesting fact is that You do not need to write any single line of code.

Here you go: TPKeyboardAvoiding - An awesome solution to handle keyboard and scroll