我有一个带有搜索栏的表格视图,我想在文本为空时进行搜索。
我希望在搜索文本为空时显示所有数据(当用户未键入任何搜索文本时)
注意 - 工作正常,输入搜索文本时,问题仅在搜索文本为空时
不幸的是,当搜索文本为空时,不会使用self.arForSearch
数组的内容。
我甚至尝试用"p"
替换文本,但数据未加载。
问题 如果用户未输入搜索字符串,如何显示所有数据?
代码粘贴在下面:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
if(searchString.length == 0)
{
searchString = @"p";
NSLog(@"string was empty but was replaced by p");
}
[self filterContentForSearchText:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)filterContentForSearchText:(NSString*)str{
// for inCaseSensitive search
str = [str uppercaseString];
NSMutableArray *ar=[NSMutableArray array];
for (NSDictionary *d in self.arForTable) {
NSString *strOriginal = [d valueForKey:@"name"];
// for inCaseSensitive search
strOriginal = [strOriginal uppercaseString];
if([strOriginal hasPrefix:str]) {
[ar addObject:d];
}
}
self.arForSearch=[NSArray arrayWithArray:ar];
NSLog(@"self.arForSearch.count = %i", self.arForSearch.count);
}
答案 0 :(得分:1)
- (void)filterContentForSearchText:(NSString*)str{
// for inCaseSensitive search
str = [str uppercaseString];
if([str isEqualToString:@""] || str == nil)
{
self.arForSearch=[NSArray arrayWithArray:self.arForTable];
}
else
{
NSMutableArray *ar=[NSMutableArray array];
for (NSDictionary *d in self.arForTable) {
NSString *strOriginal = [d valueForKey:@"name"];
// for inCaseSensitive search
strOriginal = [strOriginal uppercaseString];
if([strOriginal hasPrefix:str]) {
[ar addObject:d];
}
}
self.arForSearch=[NSArray arrayWithArray:ar];
}
NSLog(@"self.arForSearch.count = %i", self.arForSearch.count);
//updated code
[yourTable reloadData];
}
检查空字符串并将self.arForTable中的所有元素添加到self.arForSearch。
希望这会有所帮助......
更新.... 那么你可能需要添加一行[yourTable reloadData];最后会刷新表格数据
答案 1 :(得分:1)
我编写了以下代码,以便在搜索栏获得焦点时以及没有文本时显示结果。
注意:在我的应用中,搜索栏占位符等于最后插入的搜索文本,因此您可能需要调整以下代码。
//auxiliar function to force display of search results
-(void)forceDisplaySuggestionsForText:(NSString*)searchString {
UISearchDisplayController *sdc = self.searchDisplayController;
SEL sel = @selector(searchBar:textDidChange:);
if([sdc respondsToSelector:sel]){
UISearchBar *sb = sdc.searchBar;
[sdc performSelector:sel withObject:sb withObject:searchString];
}
}
- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
controller.searchBar.text = controller.searchBar.placeholder;
//this will force initial display of the search results
[self performSelector:@selector(forceDisplaySuggestionsForText:) withObject:controller.searchBar.text afterDelay:0];
}
- (void)filterContentForSearchText:(NSString*)str {
//this will force display of results when there is no text in search bar
if([str length] == 0){
[self performSelector:@selector(forceDisplaySuggestionsForText:) withObject:@" " afterDelay:0];
}
//the rest of the code for content filtering
...
}