在表视图中添加搜索栏,实现在表视图中搜索数据的功能。创建初始化表视图需要遵循UITableViewDataSource协议,设置两个数组,一个存储表视图中要搜索对象的数据,另一个存储搜索到的数据,重新加载表视图时使用。搜索功能需要遵循UISearchBarDelegate协议。
在.h文件中添加协议,创建对象:
@interface LinViewController : UIViewController<UITableViewDataSource,UISearchBarDelegate>
//创建表视图对象
@property (retain, nonatomic) UITableView * mTableView;
//创建搜索栏对象
@property (retain, nonatomic) UISearchBar * mSearchBar;
//创建可变数组对象,数组1存储初始化时表视图的数据,数组2存储搜索到的内容,重新加载表视图时使用
@property (retain, nonatomic) NSMutableArray * mArray1;
@property (retain, nonatomic) NSMutableArray * mArray2;
@end
在.m文件里添加实现的方法:
@implementation LinViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//表视图初始化
self.mTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
//⭐️设置委托对象,表视图的委托,绘制表的方法
self.mTableView.dataSource = self;
//搜索栏初始化
self.mSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.mTableView.frame.size.width, 30)];
//把搜索栏添加到表视图的表头
self.mTableView.tableHeaderView = self.mSearchBar;
//把表视图添加到当前视图中
[self.view addSubview:self.mTableView];
//⭐️设置委托对象,搜索栏的委托
self.mSearchBar.delegate = self;
//数组初始化,1-60个元素
self.mArray1 = [[NSMutableArray alloc]initWithCapacity:60];
self.mArray2 = [[NSMutableArray alloc]initWithCapacity:60];
//循环遍历,给数组元素赋值,以字符串的形式存储
for (int i = 0; i<60; i++)
{
NSString * pTempString = [NSString stringWithFormat:@"%d",i];
[self.mArray1 addObject:pTempString];
[self.mArray2 addObject:pTempString];
}
}
#pragma mark---UITableViewDataSource---加载表视图的协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//获取表视图中需要加载表的行数
return [self.mArray2 count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//设置一个静态字符串做标签,(静态防止局部变量多次创建,提高效率,节约内存)
static NSString * identifer = @"identifer";
//创建一个cell对象(利用表示图可以复用的机制)
UITableViewCell * Cell = [tableView dequeueReusableCellWithIdentifier:identifer];
//如果cell为空,就创建一个新的出来
if (nil == Cell)
{
Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
}
//获取当前表视图行数
NSInteger row = [indexPath row];
//把数组中对应元素传递给视图的文本
Cell.textLabel.text = [self.mArray2 objectAtIndex:row];
return Cell;
}
#pragma mark---UISearchBarDelegate-------搜索方法的协议
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
//清空数组2的元素
[self.mArray2 removeAllObjects];
//遍历数组1中的所有元素
for (NSString * str in self.mArray1)
{
//判断字符串与搜索栏接收到的字符是否相等
if ([str hasPrefix:searchBar.text])
{
//为数组2添加搜索到的元素
[self.mArray2 addObject:str];
}
}
//让SearchBar放弃第一响应者
[self.mSearchBar resignFirstResponder];
//重新加载视图
[self.mTableView reloadData];
}
//释放创建的对象
- (void)dealloc
{
[_mArray1 release];
[_mArray2 release];
[_mTableView release];
[_mSearchBar release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end