您的位置:首页 > 产品设计 > UI/UE

搜索框使用,UISearchBarDelegate

2016-07-16 10:53 537 查看
1.首先

@interface RootViewController :UIViewController <UISearchBarDelegate>
2.创建 它,设置代理

    _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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: