#import"TableViewController.h"
@interfaceTableViewController()
@property(nonatomic,strong)UISearchController*searchController;
@property(nonatomic,strong)NSMutableArray*listArr;
@property(nonatomic,strong)NSMutableArray*dataArr;
@implementationTableViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.listArr=[NSMutableArrayarray];
self.dataArr=[NSMutableArrayarray];
for(inti=0; i<100; i++) {
NSString*s=[NSStringstringWithFormat:@"%d",i];
[self.dataArraddObject:s];
}
self.searchController=[[UISearchControlleralloc]initWithSearchResultsController:nil];
_searchController.searchResultsUpdater=self;
_searchController.dimsBackgroundDuringPresentation=NO;
_searchController.hidesNavigationBarDuringPresentation=YES;
_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;
[self.tableViewregisterClass:[UITableViewCellclass]forCellReuseIdentifier:@"cell"];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
// Return the number of sections.
return1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
if(self.searchController.active) {
return[self.listArrcount];
}else{
return[self.dataArrcount];
}
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:@"cell"forIndexPath:indexPath];
if(self.searchController.active) {
cell.textLabel.text=self.listArr[indexPath.row];
}else{
cell.textLabel.text=self.dataArr[indexPath.row];
}
returncell;
}
-(void)updateSearchResultsForSearchController:(UISearchController*)searchController {
NSString*searchString = [self.searchController.searchBartext];
NSPredicate*preicate = [NSPredicatepredicateWithFormat:@"SELF CONTAINS
%@", searchString];
if(self.listArr!=nil) {
[self.listArrremoveAllObjects];
}
//过滤数据
self.listArr= [NSMutableArrayarrayWithArray:[self.dataArrfilteredArrayUsingPredicate:preicate]];
//刷新表格
[self.tableViewreloadData];
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
NSLog(@"%ld",indexPath.row);
}