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.
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:
ViewDidLoad()
code (as Pei explained) for instance:tableView.keyboardDismissMode = .onDrag
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With