我以编程方式创建 UISearchBar 和 UISearchDisplayController。 View Controller 是一个 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;
}
最佳答案
它不起作用,因为您将 UISearchDisplayController 创建为局部变量,这会导致它在 viewDidLoad 超出范围时被释放。因此,为您的搜索显示 Controller 创建一个强大的属性,然后它应该可以正常工作(如果您将该属性命名为 searchDisplayController,您将遇到命名冲突,因此请将其命名为其他名称)。
关于ios - 未调用 UISearchDisplayDelegate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23026393/