1、直接看代码吧
//
// ViewController.m
#import "ViewController.h"
@interface ViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
{
UITableView * _tableView;
NSMutableArray * _dataArray;
NSMutableArray * _subDataArray;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
[self configTableView];
UISearchBar * searchBar = [[UISearchBar alloc] init];
searchBar.frame = CGRectMake(0, 0, _tableView.frame.size.width, 0);
searchBar.delegate = self;
[searchBar sizeToFit]; //主动调剂大小
_tableView.tableHeaderView = searchBar;
}
- (void) configTableView {
CGFloat width = [[UIScreen mainScreen] bounds].size.width;
CGFloat height = [[UIScreen mainScreen] bounds].size.height;
CGRect tableViewFrame = CGRectMake(0, 0, width, height);
_tableView = [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStylePlain];
[self.view addSubview:_tableView];
_tableView.delegate = self;
_tableView.dataSource = self;
//备份数据源
_dataArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 100; i++) {
[_dataArray addObject:[NSString stringWithFormat:@"%i", i]];
}
//数据源
_subDataArray = [[NSMutableArray alloc] initWithArray:_dataArray];
}
#pragma mark UISearchBarDelegate
//点击键盘上得search按钮 开端调用此办法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//清空数据源
[_subDataArray removeAllObjects];
NSString * getStr = searchBar.text;
//从备份数据源查找符合条件的数据,并参加到数据源中
for (NSString * str in _dataArray) {
if ([str containsString:getStr]) {
[_subDataArray addObject:str];
}
}
//更新UI
[_tableView reloadData];
//让键盘失去第一响应者
[searchBar resignFirstResponder];
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _subDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * cellid = @"cellid";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
}
cell.textLabel.text = _subDataArray[indexPath.row];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//
// ViewController.m
#import "ViewCo