SearchBar in Navigation Bar in iOS7

2019-04-17 00:34发布

问题:

I have a tableview containing all the countries and their flags. I've been working to add a search bar and had it all working until I decided to move the search bar into the navigation bar allowed in iOS7 (for my purposes, that layout works very well).

Now, the table loads fine, the search bar shows up fine. As I type into the search bar, I can see the filtered list being built via the console. All looks good, EXCEPT the search results table never displays. In other words, I don't see the filtered list in a new tableview.

This method is being called to build the filtered list:

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope

But the standard method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

never gets called.

As I said, it's working fine when the search bar isn't in the navigation bar. I have assigned the following delegates and properties in ViewDidLoad:

searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self;

searchDisplayController.displaysSearchBarInNavigationBar = YES;

I also have:

#pragma mark - UISearchDisplayController Delegate Methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// Tells the table data source to reload when text changes
[self filterContentForSearchText:searchString scope:
 [[searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;

}

What am I missing???

回答1:

I'm running into the same issue. Everything works fine if I add the searchbar to the tableHeaderView with self.tableView.tableHeaderView = mySearchBar;

Found out something interesting: the source-tableview doesn't resize properly, so it is overlaying the results-tableview.

My app is universal. If I run it on iPad the source-tableview is covered completely, so I don't see the results-tableview. But on the iPhone it looks like this:



回答2:

I was having the same issue as Morpheus, and it was due to having self.edgesForExtendedLayout = UIRectEdgeNone; in my viewDidLoad