Reputation: 4732
I have a UITableViewController and I want to add a UISearchBarController at the top so it searches with a different table view (not the table view of the UITableViewController).
How can I initialize this via code and no IB?
@interface mySearchController : UITableViewController <UISearchDisplayDelegate, UISearchBarDelegate>
@property (nonatomic, retain) UISearchDisplayController *aSearchBarController;
@property (nonatomic, retain) UISearchBar *aSearchBar;
@end
- (id)init {
if ((self = [super init])) {
UISearchBar *tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0)];
self.aSearchBar = tempSearchBar;
self.aSearchBar.delegate = self;
[self.aSearchBar sizeToFit];
self.tableView.tableHeaderView = self.aSearchBar;
[self.aSearchBar release];
UISearchDisplayController *tempSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:aSearchBar contentsController:self];
self.searchDisplayController = tempSearchDisplayController;
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
}
return self;
}
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
// Custom initialization.
}
return self;
}
Upvotes: 1
Views: 4306
Reputation: 30846
A cursory glance at the UISearchDisplayController Class Reference
would answer your question.
"Typically you initialize a search display controller from a view controller (usually an instance of UITableViewController) that’s displaying a list. To perform configuration programmatically, set
self
for the search display controller’s view controller and search results data source and delegate."
So it should look like this:
searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchController.delegate = self;
searchController.searchResultsDataSource = self;
searchController.searchResultsDelegate = self;
If you follow this pattern, then in the table view data source and delegate methods you can check the methods’ table view argument to determine which table view is sending the message:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView)
{
return ...;
}
// If necessary (if self is the data source for other table views),
// check whether tableView is searchController.searchResultsTableView.
return ...;
}
Upvotes: 3