0

I was able to create an app using Storyboard - it has a navigation controller containing a table view controller with a search display controller and worked as expected.

I then decided to customize it by adding a UIButtonBarSystemItemSearch (magnifying glass) to the navigator bar so that when touched it would display the search bar over the navigator bar, just like setDisplaysSearchBarInNavigationBar does. To do this I removed the UISearchDisplayController from the storyboard and added it programmatically as shown in the code below. The btnSearchClicked function is called when the magnifying glass is touched, so the button is hooked up right.

My project is very similar to the Apple example project "AdvancedTableSearch" but without the scope bar.

- (IBAction) btnSearchClicked:(id)sender
{
  //Set up search bar
  UISearchBar *mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
  [mySearchBar setDelegate:self];
  [mySearchBar setShowsCancelButton:YES animated:NO];

  // Set up search display controller
  UISearchDisplayController *mySearchController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];
  mySearchController.delegate = self;
  mySearchController.searchResultsDataSource = self;
  mySearchController.searchResultsDelegate = self;
  //mySearchController.displaysSearchBarInNavigationBar = YES;
  mySearchController.navigationItem.titleView.opaque = NO;
  [self.navigationController.navigationBar addSubview:self.searchDisplayController.searchBar];
}

I am having two problems with this approach. The most important one is that even though I set the delegate properties, when I type into the search bar none of my delegate functions are called (specifically shouldReloadTableForSearchString).

The second problem is that the cancel button doesn't display despite calling the setShowsCancelButton method.

I've been learning iOS for the last year and reading everything I can find on SO, but can't figure this one out. This is my last resort and I will fall back to the old storyboard approach with standard search bar if I must. The reason I like this other approach is that I have a very long list of contacts (~5000) and don't want to have to scroll to the top to get the search bar.

  • http://stackoverflow.com/questions/8696260/creating-a-uisearchdisplaycontroller-programmatically – Hemang Feb 11 '15 at 12:51

1 Answers1

1

Looks like you're not adding the right searchDisplayController? you added self.searchDisplayController but inited a mySearchController. Try putting the last line as: [self.navigationController.navigationBar addSubview:mySearchController.searchBar];

hyouuu
  • 2,471
  • 2
  • 27
  • 37