我在InterfaceBuilder中的UITableViewController中添加了一个UISearchDisplayController。通过添加searchBar: searchBar textDidChange: searchText
方法来重新生成表的数据数组并调用reloadData
,这很容易让它工作。
但是我想在下次用户触摸搜索栏时显示之前的搜索,因为触摸(X)并清除它比再次输入更容易。但我无法做到这一点。以下是我尝试过的代码:
- (void) searchBar: (UISearchBar *) searchBar textDidChange: (NSString *) searchText {
if( searchText && [searchText length] > 0 ) {
self.displayedRows = [[NSMutableArray initWithCapacity: 1];
for( NSString *l in self.allRows ) {
NSRange r = [l rangeOfString: searchText];
if( r.location != NSNotFound )
[self.displayedRows addObject: l];
}
[self.searchDisplayController.searchResultsTableView reloadData];
}
}
- (void) searchDisplayControllerWillBeginSearch: (UISearchDisplayController *) controller {
if( self.lastSearch && [self.lastSearch length] > 0 ) {
controller.searchBar.text = self.lastSearch;
[controller.searchResultsTableView reloadData];
}
}
- (void) searchDisplayControllerWillEndSearch: (UISearchDisplayController *) controller {
self.lastSearch = controller.searchBar.text;
self.displayedRows = self.allRows;
[self.tableView reloadData];
}
下一次触摸搜索时,最后一个搜索文本在搜索栏中是相应的,我很惊讶“光标”甚至位于末尾,但搜索结果未显示,只是原始的黑暗视图搜索字段的内容为空。只要我输入一个字符,搜索结果就会更新。
我已经尝试将等效的[self.searchDisplayController.searchResultsTableView reloadData]
放入每个:
searchDisplayControllerDidBeginSearch: (UISearchDisplayController *) controller
searchDisplayController: (UISearchDisplayController *) controller didLoadSearchResultsTableView: (UITableView *) tableView
searchDisplayController: (UISearchDisplayController *) controller willShowSearchResultsTableView: (UITableView *) tableView
searchDisplayController: (UISearchDisplayController *) controller didShowSearchResultsTableView: (UITableView *) tableView
但它没有任何区别......直到我输入内容时才空白。
有没有人有任何想法如何获得预加载的搜索结果?
答案 0 :(得分:7)
你需要这样的东西:
- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
if(lastSearch.length > 0) {
NSLog(@"In searchDisplayControllerDidBeginSearch");
[self.searchDisplayController.searchBar setText:lastSearch];
}
}
如果您需要进行进一步的更改,我建议您打开UIKit
标题UISearchBar.h
和UISearchDisplayController.h
并查看可以重载的内容和位置。此外,NSLog
是您的朋友=)
只是为了解释发生了什么,以及这与...searchBar.text = lastSearch
,setText
强制textDidChange
注册的方式有何不同,后者又会重新搜索,然后调用{ {1}}。只是在不使用shouldReloadTableForSearchString
的情况下更改文本(由于某种原因)不会触发setText
。