今天第一次用UISearchBar+UISearchDisplayController感觉非常神奇。以前都是只用searchbar。看到苹果自带的搜索都是有黑色界面如图:
确不知道怎么实现的 今天就用了UISearchBar+UISearchDisplayController实现了这样的效果。
在做demo的时候发现了一些神奇的事情。
1.你完全不用tableview的reloaddata。
2.你只需要写- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchTerm这一个 searchbar的委托。就能完成以前的搜索的功能。
测试出了个问题 还要加上
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
要resetdata
}
因为tableview的绑定数据源来自同一个delegate,如果不reset,数组会出现问题
3.如果要想挡住navigationbar的话就要是navigationcontroller不能是自己添加的navigationbar,当然tabbarcontroller也对挡住。
我认为UISearchDisplayController中有自己的tableview和在你创建的tableview不是同一个对象。
如果你不想让搜索出的结果(cell)有 点击事件 就在
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath方法中判断tableview是不是你的tableview。
附上搜索的代码
- (void)resetSearch {
[maLoadData_ removeAllObjects];
[maLoadData_ addObjectsFromArray:maSource_];
}
- (void)handleSearchForTerm:(NSString *)searchTerm
{
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in maLoadData_) {
if ([key rangeOfString:searchTerm
options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:key];
}
[maLoadData_ removeObjectsInArray:toRemove];
//[table reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchTerm
{
if ([searchTerm length] == 0)
{
[self resetSearch];
//[table reloadData];
return;
}
[self handleSearchForTerm:searchTerm];
}