如何将 UISearchController 搜索栏设置为不是 tableHeaderView 或 navigationItem.titleview 的视图?

How do I set the UISearchController's searchBar to a view that isn't the tableHeaderView or navigationItem.titleview?

我试图在 table 滚动时保持搜索栏可见。目前,我将其作为 header 放置在 table 视图中,它可以正常工作,但是当您向下滚动 table 时,搜索栏当然会滚出屏幕.我想我可以简单地修改这个代码示例来做到这一点:

searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
tableview.tableHeaderView = searchContoller.searchBar // How to put it elsewhere?
//Alternative that also works
navigationItem.titleView = searchController.searchBar

我的想法是换个角度去做

otherview = searchController.searchBar

例如 UISearchBar 的出口,或空白的 UIView,或类似的东西。

但如果我这样做,它不会显示搜索栏。它似乎只能用作 table 的 header 视图或 navigationItem.titleView.

我是不是漏掉了什么?

如果你有一个空白的 UIView 放在 tableview 上面。

让我们假设您有一个名为 searchContainer 的空白 UIView 的出口。 然后,您可以通过添加以下行

UISearchController 的搜索栏添加到该视图
searchContainer.addSubview(searchController.searchBar)