iOS-UISearchBar和UISearchController(参考网友来练习一下)
#import "ViewController.h" #import "TestCell.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating> { NSMutableArray *dataArray; NSMutableArray *searchArray; UISearchController *mySearchController; } @property (weak, nonatomic) IBOutlet UITableView *myTableView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; mySearchController=[[UISearchController alloc]initWithSearchResultsController:nil]; mySearchController.searchResultsUpdater=self; mySearchController.dimsBackgroundDuringPresentation=NO; mySearchController.hidesNavigationBarDuringPresentation=NO; mySearchController.searchBar.frame=CGRectMake(mySearchController.searchBar.frame.origin.x, mySearchController.searchBar.frame.origin.y, mySearchController.searchBar.frame.size.width, 44.0 ); self.myTableView.tableHeaderView=mySearchController.searchBar; dataArray=[NSMutableArray array]; for(NSInteger i=0;i<100;i++) { [dataArray addObject:[NSString stringWithFormat:@"%ld-test",(long)i]]; } } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (mySearchController.active) { return searchArray.count; } else { return dataArray.count; } } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 44; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TestCell *testCell=[tableView dequeueReusableCellWithIdentifier:@"TestCell" forIndexPath:indexPath]; if (mySearchController.active) { testCell.testLabel.text=searchArray[indexPath.row]; } else { testCell.testLabel.text=dataArray[indexPath.row]; } return testCell; } -(void)updateSearchResultsForSearchController:(UISearchController *)searchController { NSString *searchString=mySearchController.searchBar.text; NSPredicate *predicate=[NSPredicate predicateWithFormat:@"self contains[c]%@",searchString]; if (searchArray.count) { [searchArray removeAllObjects]; } searchArray=[NSMutableArray arrayWithArray:[dataArray filteredArrayUsingPredicate:predicate]]; [_myTableView reloadData]; } @end