2015-09-25 16 views
0

實現UISearchController我下面這個教程在我的項目實施UISearchControllerhttp://useyourloaf.com/blog/updating-to-the-ios-8-search-controller.html在UITableView的Objective-C的

我成功找到與方法已過時(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

首先,您應該檢查self.searchResults.count。如果self.searchResults.count > 0,方法searchForText:searchString是正確的。所以你在tableView中檢查問題。

+0

感謝您的回覆!我在哪裏檢查self.searchResults.count> 0?這在cellForRow中不起作用(從不> 0) – Viny76

+0

您可以在行'self.searchResults = [self.allUsers filteredArrayUsingPredicate:predicate];'之後檢查。確保文本輸入包含在self.allUsers中。 – nynohu

+0

解決!!!!謝謝,我改變了我的cellForRow與條件:self.searchResults.count> 0,同上numberOfRowsInSection! :) – Viny76