您的位置:首页 > 产品设计 > UI/UE

ios开发之uiTableView增加搜索框

2016-07-01 10:31 309 查看


ios开发之uiTableView增加搜索框

此方法通用,即ios8之前和之后都可以用。虽然UISerachController在ios8以后代替了UISearchBar和UISearchDisplayController,但是呢,你这样让ios8以前的系统情何以堪。考虑到兼容性问题,还是不使用UISerachController。

因为表格内容是从服务器获取的,不方便做成Demo,以后有机会再整理,大家不懂的可以一起讨论。

.h文件定义变量

@property (strong,nonatomic) NSMutableArray  *searchList;//保存搜索结果


.m文件

1.定义变量

@interface PlateProcessWidget()
{
UISearchBar  *  searchBar;
UISearchDisplayController *  searchDc;
}
@end


2.在ViewDidLoad中,uiTableView头部增加搜索框控件并设置相应代理

searchBar=[[UISearchBar  alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
searchBar.tintColor=[UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:1.0f];
searchBar.autocorrectionType=UITextAutocorrectionTypeNo;
searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
searchBar.keyboardType=UIKeyboardTypeAlphabet;
searchBar.hidden=NO;
searchBar.placeholder=[NSString stringWithCString:"请输入需要查找的订单号"  encoding: NSUTF8StringEncoding];
searchBar.delegate=self;
_tableView.tableHeaderView=searchBar;

searchDc=[[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];

searchDc.searchResultsDataSource=self;
searchDc.searchResultsDelegate=self;
searchDc.delegate=self;
[searchDc  setActive:NO];


3.修改UITableView代理里面的两个方法:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView==_tableView)
{
return _hasNextPage?self.listData.count+1:self.listData.count;
}
else
{
return self.searchList.count;
}

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


if (tableView==_tableView)
{
if (indexPath.row < self.listData.count) {
cellIdentifier = self.cellIdentifier;
info = [self.listData objectAtIndex:indexPath.row];
}
else {
cellIdentifier = @"MoreCell";
}
}
else
{
if (indexPath.row < self.searchList.count) {
cellIdentifier = self.cellIdentifier;
info = [self.searchList objectAtIndex:indexPath.row];
}
else {
cellIdentifier = @"MoreCell";
}
}



4.实现SearchBar代理中的方法,即检测有文本输入时激活此方法,以便实时显示搜索结果

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self filterBySubString:searchText];
}


-(void)filterBySubString:(NSString*)searchString
{
NSPredicate *prediction=[NSPredicate predicateWithFormat:@"self.orderNo contains %@",searchString];//最重要的谓词定义,self表示UITableView的一个Cell,.orderNo表示Cell中显示对象的一个字段
if (self.searchList!=nil) {
[self.searchList removeAllObjects];
}
self.searchList=[[NSMutableArray alloc] initWithArray:self.listData ];//将搜索前的UITableView内容给搜索后的UITableView
[self.searchList filterUsingPredicate:prediction];//根据前面的谓词定义对搜索后的UITableView进行过滤
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: