1.首先
@interface RootViewController :UIViewController <UISearchBarDelegate>
_searchBar = [[UISearchBaralloc]initWithFrame:CGRectMake(0,0,320,30)];
_searchBar.delegate =self;
_tableView.tableHeaderView =_searchBar;
//UISearchDisplayController与搜索框关联后当在搜索框中输入内容时,会弹出一个UISearchDisplayController自己创建的TableView把我们原来的TableView覆盖。UISearchDisplayController的searchResultsDataSource searchResultsDelegate分别是其创建的那个Tableview的dataSource和delegate属性
//这里我们把自己创建的TableView(_tableView)和UISearchDisplayController创建的TableView的代理都设成了self,所以在相应的事件处理函数里需要判断触发事件的到底是哪个TableView.
UISearchDisplayController *searchDisplayController = [[UISearchDisplayControlleralloc]initWithSearchBar:_searchBarcontentsController:self];
searchDisplayController.searchResultsDataSource =self;
searchDisplayController.searchResultsDelegate =self;
3.代理方法
//定制搜索框的取消按钮,纯粹是摸索出来的仅供参考。
- (void)customSearchBar
{
for (UIView *viewin [_searchBar.subviews[0]subviews]) {
if ([viewisKindOfClass:UIButton.class]) {
UIButton *button = (UIButton *)view;
[button setTitle:@"取消"forState:UIControlStateNormal];
}
}
}
#pragma mark-UISearchBarDelegate
//UISearchBarDelegate协议中定义的方法,当开始编辑时(搜索框成为第一响应者时)被调用。
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton =YES;
[self customSearchBar];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
[_tableViewreloadData];
}
本文详细介绍如何在iOS应用中实现UISearchBar,并将其与UITableView结合使用。文章包括配置UISearchBar的步骤、设置代理方法来监听搜索行为以及自定义取消按钮等关键操作。
723

被折叠的 条评论
为什么被折叠?



