在UITableView Objective-C中实现UISearchController

时间:2015-09-25 00:33:26

标签: ios objective-c uitableview uisearchbar uisearchcontroller

我正在按照本教程在我的项目中实施UISearchControllerhttp://useyourloaf.com/blog/updating-to-the-ios-8-search-controller.html

我成功找到了已弃用的方法(searchDisplayController),但我希望实现UISearchController

好吧,在我的viewDidLoad中,我实现了:

//UISearchController
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.searchBar.scopeButtonTitles = @[];
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];

在我的numberOfRowsInSection中,我已将旧代码用于searchDisplayController

if (table == self.searchDisplayController.searchResultsTableView)
{
    return [self.searchResults count];
}
else
{
    return [self.allUsers count];
}

在我的cellForRowAtIndexPath

NSArray *sourceData = (tableView == self.searchDisplayController.searchResultsTableView ? self.searchResults : self.allUsers);
PFUser *selected = [sourceData objectAtIndex:indexPath.row];
NSString *name = [[sourceData objectAtIndex:indexPath.row] valueForKey:@"surname"];
cell.textLabel.text = name;

并添加了以下方法:

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *searchString = searchController.searchBar.text;
    [self searchForText:searchString];
    [self.tableView reloadData];
    NSLog(@"updateSearchResultsForSearchController");
}

- (void)searchForText:(NSString*)searchText
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"surname contains[c] %@", searchText];
    self.searchResults = [self.allUsers filteredArrayUsingPredicate:predicate];

}

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
{
    [self updateSearchResultsForSearchController:self.searchController];
}

好吧,当我点击搜索栏并点按某些字词时,会显示日志updateSearchResultsForSearchController。但我搜索的人没有出现。我不知道我要为这项工作实施什么?也许我的searchForText:searchString方法不正确?

或者我可能会在cellForRowAtIndexPathnumberOfRowsInSection

中添加内容

1 个答案:

答案 0 :(得分:1)

首先,您应该检查self.searchResults.count。如果self.searchResults.count > 0,方法searchForText:searchString是正确的。所以你检查tableView中的问题。