search Bar and Search Display Controller是ios自带的有动画效果的搜索栏,与tableView配合使用效果很好。
在xib或storyboard中拖一个tableView和search Bar and Search Display Controller,连接delegate和data source。
实现UISearchBarDelegate:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSString *keyword = [[self.searchDisplayController.searchBar text] stringByReplacingOccurrencesOfString:@" " withString:@""]; // 去掉搜索内容的多余空格
if ([UtilsFunction checkNullString:keyword]) {
return;
}
[self getSearchResultFromServer:keyword];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSString* keyword = [[self.searchDisplayController.searchBar text] stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([UtilsFunction checkNullString:keyword]) { // 检查字符串是否为空
return ;
}
[self getSearchResultFromServer:keyword];
[searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
searchBar.text = @"";
searchBar.text = @"";
[searchBar resignFirstResponder];
searchBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar
selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
searchBar.showsCancelButton = YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
searchBar.showsCancelButton = NO;
}
在tableView的delegate和data Source方法中都需判断
if(tableView == self.searchDisplayController.searchResultsTableView),这样搜索结果才会显示在搜索框的tableView之上
[self.searchDisplayController.searchResultsTableView reloadData];