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

风格不统一 提交于 2019-12-08 01:02:14

问题


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?


回答1:


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;
}



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/26305791/objective-c-xcode-6-best-way-to-have-a-search-bar-populate-a-table-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!