search Bar and Search Display Controller的使用

本文介绍如何在iOS应用中集成searchBarandSearchDisplayController组件,并与tableView配合使用来实现搜索功能。文章提供了UISearchBarDelegate方法的具体实现,确保了搜索栏具备基本的搜索、取消等操作,并展示了如何从服务器获取搜索结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值