views:

303

answers:

2

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?

+1  A: 

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

@end

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

#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)];
}

@end

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.

Matt Long
A: 

Y dont u try ...... UISearchDisplayController

Just define these in ur .h file

IBOutlet UISearchBar* mySearchBar; UISearchDisplayController* mySearchDisplayController; IBOutlet UITableView* myTableView;

and handle UISearchBarDelegate in .h

now in .m file just write these code

mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self]; mySearchDisplayController.searchResultsDelegate = self; mySearchDisplayController.searchResultsDataSource = self; mySearchDisplayController.delegate = self;

I hope this might help .......

Amit