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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。