UISearchController实现搜索

转载自:http://www.tuicool.com/articles/6viqEn


可以通过 UISearchController 实现 UISearchResultsUpdating 这个委托实现搜索的效果;

视图中中需要声明UISearchResultsUpdating:

@interface ViewController : UITableViewController<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating>

@end

属性声明:

@property (nonatomic, strong) UISearchController *searchController;

需要自己初始化一下UISearchController:

_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = NO;
_searchController.hidesNavigationBarDuringPresentation = NO;
[_searchController.searchBar sizeToFit];
self.tableView.tableHeaderView = self.searchController.searchBar;

直接使用self.searchController.active可判断当前状态是否为正在搜索,也就是UISearchController的active属性:

//设置区域的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
			if (self.searchController.active) {
				return [self.searchList count];
			}else{
				return [self.dataList count];
			}
}
//返回单元格内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString *flag=@"cellFlag";
	UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
	if (cell==nil) {
		cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag];
	}
	if (self.searchController.active) {
		[cell.textLabel setText:self.searchList[indexPath.row]];
	}
	else{
		[cell.textLabel setText:self.dataList[indexPath.row]];
	}
	return cell;
}

具体调用的时候使用updateSearchResultsForSearchController进行结果过滤:

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
	NSString *searchString = [self.searchController.searchBar text];
	NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
	if (self.searchList!= nil) {
		[self.searchList removeAllObjects];
	}
	//过滤数据
	self.searchList= [NSMutableArray arrayWithArray:[_dataList filteredArrayUsingPredicate:preicate]];
	//刷新表格
	[self.tableView reloadData];
}

如果在选择某项后需要恢复到未搜索状态,可以设置一下searchController的活动状态即可:

    self.searchController.active = NO;

如果你发现点击某一项进入二级页面后,顶上的searchBar还在的话,你可以使用下面的方法让它不跟过去:

    self.definesPresentationContext = YES;

这一行写在viewDidLoad里面就可以的,这个解决方案是参考这篇文章的:http://blog.csdn.net/codingfire/article/details/53538495


效果演示:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值