iOS 11 上 UITableView 中的 UISearchController 问题

Posted

技术标签:

【中文标题】iOS 11 上 UITableView 中的 UISearchController 问题【英文标题】:Issue with UISearchController in UITableView on iOS 11 【发布时间】:2017-12-28 12:39:19 【问题描述】:

iOS 11 我在表格的标题视图上有一个UITableViewController 和一个UISearchController,使用以下代码:

if(searchController == nil)

    searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    searchController.dimsBackgroundDuringPresentation = false;
    searchController.searchResultsUpdater = self;
    searchController.searchBar.delegate = self;
    self.definesPresentationContext = NO;
    searchController.delegate = self;

self.tableView.tableHeaderView = searchController.searchBar;

[self.tableView setContentOffset:CGPointMake(0,searchController.searchBar.bounds.size.height) animated:YES];

当我运行应用程序时,我想要的行为完全适用于行数超过设备屏幕高度的 tableview,但在 tableview 只有几行的情况下,搜索栏正在从导航栏下降一点。

When there are few cells on the tableview, the search bar drops down as in this picture

When there are more cells on the tableview, the search bar doesn't drop down

【问题讨论】:

【参考方案1】:

ios 11 上,带有 tableView 标头的 UISearchController 的行为发生了变化,现在它是 navigationItem 的一部分,您不需要 tableView。因此,您必须检查 iOS >= 11 并执行以下操作

if (@available(iOS 11.0, *)) 
    self.navigationItem.searchController = searchController;
// ToDo : dont forget to hide the tableView 
// ...       
 else 
    self.tableView.tableHeaderView = searchController.searchBar;
    [self.tableView setContentOffset:CGPointMake(0,searchController.searchBar.bounds.size.height) animated:YES];

【讨论】:

我有一个要求,我必须仅在 tableview 标题上使用搜索。这就是为什么我正在寻找一种方法来做到这一点。 这是个非常糟糕的主意,iOS 11 尤其是 iPhone X 会有很多麻烦... @AbidMohamedSadok ,你有这个工作吗?在ios 11中,如果在导航项(导航栏的一部分)中,那么如果我需要导航标题+搜索栏作为表头怎么办?

以上是关于iOS 11 上 UITableView 中的 UISearchController 问题的主要内容,如果未能解决你的问题,请参考以下文章

iOS11出现键盘时UITableView将键盘高度添加到contentSize

iOS 修改UITableView separator

iOS 编辑UITableView(根据iOS编程编写)

uitableview中的ios进度条

iOS UITableView左滑操作功能的实现(iOS8-11)

UITableView scrollToRow 在添加新行后不再适用于 iOS 11