很多开发者在使用uitableview的时候根据需求会添加uisearchbar,方便用户搜索,该功能也好实现。
重点注意问题:需要将uisearchbar设置为uitableview 的tableheaderview,因为在cell个数*cell高度和view高度+uisearchbar相等时tableview貌似就不滚动了,但是设置为tableheaderview就没问题哦,同时最诡异的问题是tableheaderview在tableview的section滚动到定不是竟然滚动,不是停留在最顶端。
1:使用xib,添加UISearchDisplayController,控件即可,会自动关联好相关属性,你只需关联uisearchbar就行,并设置为uitableview 的tableheaderview。
2:使用代码编码,在尝试用代码过程中出现了问题,按照逻辑UISearchDisplayController 在alloca后需要autorelease,因为UIViewController别的地方不再使用 ,但是问题就出现在这里,如果你autorelease了,则不能实现系统的搜索功能,具体原因见:http://stackoverflow.com/questions/7679501/uiviewcontroller-does-not-retain-its-programmatically-created-uisearchdisplaycon,处理方法里面也提供了。
下面是大致代码:
self.tableViewHeaderSearchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, kSearchBarH)] autorelease];
self.tableViewHeaderSearchBar.delegate = self;
uitableview 的tableheaderview = self。tableViewHeaderSearchBar;
_searchDisCon = [[UISearchDisplayController alloc] initWithSearchBar:self.tableViewHeaderSearchBar contentsController:self]; 注意这个地方不要autorelease,需要赋值给私有变量,析构的时候处理
_searchDisCon.delegate = self;
_searchDisCon.searchResultsDataSource = self;
_searchDisCon.searchResultsDelegate = self;
实现相关代理即可。处理过程中最好做成base类方便子类使用。
效果问题。如果你使用的是系统的navigationbar,恭喜你,点击searchbar的时候它会自动隐藏,取消搜索的时候会自动显示。如果你使用的是自定义的,意思是非继承系统的navigationbar,则需要手动处理navigationbar的隐藏和显示,添加相关动画即可。
如下:
- (void)searchViewHide:(BOOL)hide
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
CGRect frame = self.navigationBar.frame;
int customNavH = frame.size.height;
if(hide)
{
[self.tableView setFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height - customNavH)];
frame.origin.y = 0;
[self.navigationBar setFrame:frame];
}else
{
[self.tableView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 460)];
frame.origin.y = -frame.size.height;
[self.navigationBar setFrame:frame];
}
[UIView commitAnimations];
}
在一下代理中触发即可:- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
通过上面就可以实现系统的搜索效果,根据自己的业务需求微调即可。