H K
H K

Reputation: 1275

Objective-C/Xcode 6: Best way to have a Search Bar populate a table view?

I have table view with a Search Bar above it. My intention is to have users enter a query in the search bar and have the table view populate with results - either when the user presses enter or as they're typing.

After reading a number of tutorials, I selected the Search Bar and Search Display Controller for the Search Bar. However, it seems this controller is less of an enter-query-then-display-results tool than a filter-existing-table-view-data tool. This means I'm coming upon a table view that already has all the data and is filtered as I type -- what I'd like is to come upon an empty table view and have it populate.

I was wondering if there was a way to use the Search Bar and Search Display Controller to achieve the effect I want or it there was a preferred way?

Upvotes: 2

Views: 7401

Answers (3)

ansible
ansible

Reputation: 3579

When using UISearchDisplayController you'll have two UITableViews. The one in your search view controller. So assuming you are hooking up both UITableView's dataSources to your UIViewController, just check which table is being passed in and return nothing if it's not for the search.

For example

- (NSArray *) _sectionArrayForTable:(UITableView *) tableView {
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        // Return your search results
    }

    // Show nothing when not searching
    return 0;
}

Upvotes: 1

c_rath
c_rath

Reputation: 3628

These two Ray Wenderlich tutorials are great for learning how to implement search into your UITableViews.

This tutorial covers the basic Search Bar with Objective-C. This tutorial covers the Search Bar using Swift.

Basically (very basic implementation level here) you will want to know if you are searching or not. If you are not searching, in your tableView:numberOfRowsInSection: method you can return 0, otherwise return the count of the results. Then in your tableView:cellForRowAtIndexPath: method you can customize the cell that is being displayed based upon the results.

Upvotes: 2

Zach
Zach

Reputation: 1

When the text changes, you will want to determine which results to show for that string and update some array or dictionary. Implement the tableview datasource methods to show the contents of that array/dictionary and call reload table when the text changes

Upvotes: 0

Related Questions