Thursday, July 8, 2010

Hiding the keyboard when using UISearchBar and UITableView

In one of my recent applications, I set up a UIViewController containing a UISearchBar and a UITableView. I implemented all the necessary delegate methods for both classes, and my search was working just fine (after working out a few kinks..). I did have one remaining problem though... Since I was searching as the user was typing, similar to an autocomplete on the web, the results were automatically being shown in the tableview but the keyboard was still there! This only showed the user a few results and was not very user friendly. I next figured out how to hide the keyboard once the user touched the tableview and started scrolling.

It's actually really easy to do this - all you have to do is implement the UIScrollViewDelegate as follows:

@interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

...and then put the following into your class.m source:

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

3 comments: