首页 > 代码库 > 代码实现搜索框

代码实现搜索框

1.在.h文件中添加两个协议 

UISearchBarDelegate,UISearchResultsUpdating

技术分享

2..m文件里面,直接代码构建,不需要拖控件

_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

    _searchController.searchResultsUpdater = self;

    _searchController.dimsBackgroundDuringPresentation = NO;

    _searchController.hidesNavigationBarDuringPresentation = NO;

    _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);

    self.tableview.tableHeaderView = self.searchController.searchBar;

技术分享

3.搜索需实现的一个函数

searchController{

    

    NSString *searchString = [self.searchController.searchBar text];

    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"itemName contains[c] %@",searchString];

    if (self.searchResult!=nil) {

        [self.searchResult removeAllObjects];

    }

    // 过滤数据

    self.searchResult = [NSMutableArray arrayWithArray:[_toDoList filteredArrayUsingPredicate:preicate]];

    //刷新数据

    [self.tableview reloadData];

 

 

技术分享

代码实现搜索框