在使用UISearchController的过程中遇到了很多问题,踩过了很多坑,现在记录并总结一下。
1. 第一个问题就是sectionIndex和Searchbar的冲突
searchBar加到tableView的headerView上,然后为tableView添加sectionIndex,问题就出来了,因为sectionIndex会占用位置,tableView整体左移,searchBar也不例外。
通过Google查找资料找到了解决方案,就是清楚sectionIndex的背景并把searchbar添加到一个UIView上然后再加载tableHeaderView使用就可以解决。如下
[self.productListTableView setSectionIndexBackgroundColor:[UIColor clearColor]];
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _brandListTableView.bounds.size.width, _searchController.searchBar.size.height)];
[headerView addSubview:self.searchController.searchBar];
//设置tableHeaderView
[self.productListTableView setTableHeaderView:headerView];
2.第二个问题就是搜索的时候searbar会向上移64
当在有navigation的时候点击,搜索时,searchBar向上偏移64,网上的解决方案是:
self.definesPresentationContext = YES;
设置definesPresentationContext为YES,可以保证在UISearchController在激活状态下用户push到下一个view controller之后search bar不会仍留在界面上。
苹果对它官方的解释是// know where you want UISearchController to be displayed
a、如果不添加上面这行代码,在设置hidesNavigationBarDuringPresentation 这个属性为YES的时候,搜索框进入编辑模式会导致,searchbar不可见,偏移-64;
在设置为NO的时候,进入编辑模式输入内容会导致高度为64的白条,猜测是导航栏没有渲染出来
b、如果添加了上面这行代码,在设置hidesNavigationBarDuringPresentation这个属性为YES的时候,输入框进入编辑模式正常显示和使用;在设置为NO的时候,搜索框进入编辑模式导致向下偏移64。
3.搜索结果tableView会向上偏移20px
解决方法是让控制器不自动滚动,设置如下
self.automaticallyAdjustsScrollViewInsets = NO;