views:

1058

answers:

2

What I want:

A UIView with a UISearchBar at the top. Starting to edit the searchBar dims the current view and shows search results from another [UITableView]Controller.

What I've tried:

In Interface Builder:

  • add a "Search Bar and Search Display Controller" to the UIView.
  • add a placeholder object for my UITableViewController
  • add a UITableView object and set it as the view for the UITableViewController
  • set the delegate for the UISearchBar to the UITableViewController
  • set all the outlets on the UISearchDisplayController to the UITableViewController

In Code:

  • add the UISearchBarDelegate, UISearchDisplayDelegate protocols to the UITableViewController

What I'm getting:

Tapping to edit the search field crashes the app. No error messages, and only the "viewDidLoad" method in the UITableViewController gets called.

In Conclusion:

How do I go about using an external controller for a UISearchBar that is in a UIView?

A: 

For one thing, if your Controller class is extending from UITableViewController, you can't have a search bar in it if you're using Interface Builder. Instead, extend from UIViewController and conform to the Table Data Source and Delegate protocols on your own.

But yeah, for that answer to be a good one for you, you're going to have to add some code or something to your question.

bpapa
I don't want the search bar in the UITableViewController. I want that controller to provide a tableView of results to the UISearchBar that is in another view, which is controlled by a separate viewcontroller.
Kelso.b
You should only have one view controller per screen according to Apple's guidelines.
bpapa
+1  A: 

Ok, so I've figured it out. I swear this is one of the first things I tried, but obviously I didn't do it correctly.

In my UIViewController (the one that has the UISearchBar in it), I instantiate a UISearchDisplayController:

// sb = IBOutlet UISearchBar  
sc = [[SearchController alloc] initWithStyle:UITableViewStylePlain];  
sdc = [[UISearchDisplayController alloc] initWithSearchBar:sb contentsController:sc];  
sb.delegate = sc;  
sdc.delegate = sc;  
sdc.searchResultsDelegate = sc;  
sdc.searchResultsDataSource:sc = sc;  `

Where SearchController is my subclass of UITableViewController and adapts the UISearchBarDelegate and UISearchDisplayDelegate protocols.

Now that I think about it, using one linked from IB would probably work just as well (and in the same way)...

So the above works for me, but now the results tableView doesn't show up unless I manually add it to the main view: [self.view addSubview:sc.tableView]; but that's fodder for another question, I suppose.

There isn't any documentation on the web (as far as my google-fu is concerned) of a non-self-delegated UISearchDisplayController, so hopefully this helps out another Obj-C noob someday.

Kelso.b