我以编程方式创建了一个UISearchBar和UISearchDisplayController。视图控制器是一个UITableViewController。 @interface StockTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate>
您可以看到以下代码。但是当我在搜索栏中输入时,不会调用shouldReloadTableForSearchString,包括其他UISearchDisplayDelegate方法。
- (void)viewDidLoad
{
[super viewDidLoad];
self.searchResults = [NSArray array];
UISearchBar *searchBar = [[UISearchBar alloc] init];
searchBar.barStyle = UISearchBarStyleDefault;
searchBar.searchBarStyle = UISearchBarStyleDefault;
searchBar.showsCancelButton = YES;
searchBar.showsScopeBar = NO;
searchBar.delegate = self;
UISearchDisplayController *searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self;
self.tableView.tableHeaderView = searchBar;
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
NSLog(@"searching"); //not showed up in the console
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
NSLog(@"%@", searchString); //not showed up in the console
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE %@", searchString];
NSArray *results = [Stock MR_findAllSortedBy:@"createdDate" ascending:NO withPredicate:predicate];
if ([results count] > 0) {
self.searchResults = results;
[self.searchDisplayController.searchResultsTableView reloadData];
}
return YES;
}
答案 0 :(得分:11)
它不起作用,因为您正在将UISearchDisplayController创建为局部变量,这会导致在viewDidLoad超出范围时将其解除分配。因此,为搜索显示控制器创建一个强大的属性,然后它应该正常工作(如果你命名属性,你将会遇到命名冲突,searchDisplayController,所以称之为其他)。