在当前窗口的根视图控制器的.h文件中,添加几个属性如下
@property (retain,nonatomic) UISearchBar *mySearchBar;
@property (retain,nonatomic) UITableView *myTableView;
@property (retain,nonatomic) NSMutableArray *array1;
@property (retain,nonatomic) NSMutableArray *array2;
#import "liViewController.h"
@interface liViewController ()
@end
@implementation liViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//定义一个临时的表视图
UITableView *tempTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
//初始化表视图
self.myTableView = tempTableView;
//释放掉临时变量
[tempTableView release];
//初始化searchBar
self.mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 30)];
//为表视图的表头视图赋值
self.myTableView.tableHeaderView = self.mySearchBar;
//设置UITableViewDataSource的代理
self.myTableView.dataSource = self;
//设置UISearchBarDelegate的代理
self.mySearchBar.delegate = self;
//加载表视图在当前视图上
[self.view addSubview:self.myTableView];
//初始化两个数组
self.array1 = [[NSMutableArray alloc]initWithCapacity:60];
self.array2 = [[NSMutableArray alloc]initWithCapacity:60];
//为数组赋值
for (int i = 0; i < 60; i ++)
{
NSString *pString = [NSString stringWithFormat:@"%d",i];
[self.array1 addObject:pString];
[self.array2 addObject:pString];
}
}
#pragma mark ---datasourceDelegate---
//实现协议中的两个必须实现的方法
//返回显示出来的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.array1 count];
}
// 渲染每一行
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//定义静态变量,防止局部变量多次重复调用
static NSString *identifier = @"identifier";
//用已有的行初始化新的行
UITableViewCell *pCell = [tableView dequeueReusableCellWithIdentifier:identifier];
//确定pCell不为空
if (nil == pCell)
{
pCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
//每一行的内容
pCell.textLabel.text = [self.array1 objectAtIndex:[indexPath row]];
return pCell;
}
#pragma mark ---searchBar delegate ---
//实现UISearchBarDelegate协议
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
//清除掉数组array1的内容
[self.array1 removeAllObjects];
//遍历整个数组,寻找要超着的内容
for (NSString *pStr in self.array2)
{
if ([pStr hasPrefix:self.mySearchBar.text])
{
//把以要查找的字符串为开头的字符串保留到array1中,用于展示
[self.array1 addObject:pStr];
}
}
//让searchBar按钮放弃第一响应
[self.mySearchBar resignFirstResponder];
[self.myTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) dealloc
{
[_array1 release];
[_array2 release];
[_mySearchBar release];
[_myTableView release];
[super dealloc];
}
@end