UISearchBar 在活动时与 UITableView 内容重叠

UISearchBar overlaps with UITableView content when active

我有一个带有 table 视图和 UISearchController 的视图控制器。当 运行 应用程序时,我发现搜索栏在活动时与内容重叠。我需要调整什么才能使搜索栏处于活动状态时内容不重叠?

普通视图:

搜索栏处于活动状态:

查看控制器设置:

您可以这样使用“UISearchController”:

_searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
self.searchController.searchResultsUpdater = self;
[self.searchController.searchBar sizeToFit];
self.tableView.tableHeaderView = self.searchController.searchBar;

// we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
self.resultsTableController.tableView.delegate = self;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others

// Search is now just presenting a view controller. As such, normal view controller
// presentation semantics apply. Namely that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
//
self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed

您可以使用此工作 Apple Reference Sample code 了解更多详细信息。

问题是因为你有automaticallyAdjustsScrollViewInsets = true

请取消选中

会有帮助:)

尝试将 SearchBar 放在 TableView 的 header 中。

这与在 iOS 11 上滚动时取消隐藏搜索栏有关。

if #available(iOS 11.0, *) {
  navigationItem.searchController = searchController
  navigationItem.hidesSearchBarWhenScrolling = false
} else {
  // Fallback on earlier versions
  tableView?.tableHeaderView = searchController.searchBar
}

在你的 viewDid() 中写这个。

来源:apple

if #available(iOS 11.0, *) {
    // For iOS 11 and later, place the search bar in the navigation bar.
    navigationItem.searchController = searchController

    // Make the search bar always visible.
    navigationItem.hidesSearchBarWhenScrolling = false
} else {
    // For iOS 10 and earlier, place the search controller's search bar in the table view's header.
    tableView.tableHeaderView = searchController.searchBar
}