quantum quantum - 1 year ago 107
iOS Question

Tap on empty UITableView to resign search bar

I've got a tableview with a search bar at the top. When I click on the search, it is called to first responder and the keyboard appears. The search bar has a cancel button, but when the table is empty I want the user to be able to tap anywhere on the empty table rows to resign the search bar and keyboard as first responder. How do I do this?

Answer Source

You'll have to create your own UITableView class that overrides the touchesEnded method. Then you can call back to your delegate, which should be your view controller, and tell it to tell your UISearchBar to resign first responder.

The UITableView derived class would look something like this:

#import <UIKit/UIKit.h>

@interface FRTableView : UITableView {


// ------------------------------

#import "FRTableView.h"

@implementation FRTableView

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    return self;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    [super touchesEnded:touches withEvent:event];
    NSLog(@"Touches ended");

    // Bubble back up to your view controller which should be this
    // table view's delegate.
    if ([self delegate] && [[self delegate] respondsToSelector:@selector(touchEnded)])
        [[self delegate] performSelector:@selector(touchEnded)];


Make sure you set your table view in Interface Builder to use your custom class instead of the normal UITableView class. Then in your view controller, implement the selector I've called touchEnded like this:

- (void)touchEnded;
    NSLog(@"Back in root view controller.");
    [searchBar resignFirstResponder];

Where searchBar is an IBOutlet connected to a UISearchBar in Interface Builder.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download