iOS8之后我们就可以直接运用UISearchController的代理方法进行开发,不用再UIsearch和其他的一下东西了,我就直接给大家上代码吧
UISearchBarDelegate,UISearchResultsUpdating这两个代理方法
viewdidload:
self.dataList=[NSMutableArray arrayWithCapacity:100]; for (NSInteger i=0; i<100; i++) { [self.dataList addObject:[NSString stringWithFormat:@"%ld-FlyElephant",(long)i]]; } ALog(@"-====%lu",(unsigned long)self.dataList.count); tableview =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain]; tableview.delegate =self; tableview.dataSource =self; [self.view addSubview:tableview]; _search =[[UISearchController alloc]initWithSearchResultsController:nil]; _search.searchResultsUpdater =self; _search.dimsBackgroundDuringPresentation = NO; _search.hidesNavigationBarDuringPresentation = NO; _search.searchBar.frame = CGRectMake(_search.searchBar.frame.origin.x, _search.searchBar.frame.origin.y, _search.searchBar.frame.size.width, 44);//当做表的头视图 tableview.tableHeaderView = _search.searchBar;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {//一定要判断状态 if (_search.active) { return [self.searchList count]; } else{ return [self.dataList count]; } } -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *flag=@"cellFlag"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag]; if (cell==nil) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag]; } if (_search.active) { [cell.textLabel setText:self.searchList[indexPath.row]]; } else{ [cell.textLabel setText:self.dataList[indexPath.row]]; } return cell; } -(void)updateSearchResultsForSearchController:(UISearchController *)searchController { NSString *searchString =[_search.searchBar text];//筛选语句 NSPredicate *predicate =[ NSPredicate predicateWithFormat:@"SELF CONTAINS[c]%@",searchString]; if (self.searchList !=nil) { [self .searchList removeAllObjects]; } self.searchList = [NSMutableArray arrayWithArray:[self.dataList filteredArrayUsingPredicate:predicate]]; ALog(@"-==%ld",self.searchList.count); [tableview reloadData]; }
时间: 2024-11-13 08:05:29