UISearchController 在 segue 之后持续存在

UISearchController persisting after segue

我有一个带有 UISearchController 的应用程序。 UI 的这个元素完全用这样的代码设置:

searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.searchBarStyle = UISearchBarStyle.Minimal

searchController.searchBar.frame = CGRectMake(searchController.searchBar.frame.origin.x, searchController.searchBar.frame.origin.y, searchController.searchBar.frame.size.width, 44.0)

然后我将它添加到我的 tableView 的 tableHeaderView

tableView.tableHeaderView = searchController.searchBar

一切似乎都运行良好,但是当它处于活动状态并且我 select 我的 table 视图中的一个项目时,我的应用程序转至另一个视图控制器,搜索控制器保留在视图中。我不确定这是怎么可能的,因为搜索控制器应该是另一个视图控制器中 table 视图的子视图。我怎样才能防止这种情况发生?

您可以通过在 prepareForSegue 中将活动 属性 设置为 false 来手动隐藏 searchController。在 prepareForSegue()

中添加以下代码
searchController.active = false

或者,您应该在 viewDidLoad() 中添加以下行以获得默认行为

definesPresentationContext = true

来自 definesPresentationContext

的文档

A Boolean value that indicates whether this view controller's view is covered when the view controller or one of its descendants presents a view controller.

讨论

When a view controller is presented, iOS starts with the presenting view controller and asks it if it wants to provide the presentation context. If the presenting view controller does not provide a context, then iOS asks the presenting view controller's parent view controller. iOS searches up through the view controller hierarchy until a view controller provides a presentation context. If no view controller offers to provide a context, the window's root view controller provides the presentation context.

If a view controller returns true, then it provides a presentation context. The portion of the window covered by the view controller's view determines the size of the presented view controller's view. The default value for this property is false.

重要说明(来自评论中的@paulvs)

Little gotcha. Set definesPresentationContext on the view controller, not the search controller, I think this is worth emphasising.

如果您管理自己的转换并使用 popToViewController 离开视图,请在 searchController 而不是视图上提供上下文

searchController.definesPresentationContext = true

否则会报错

popToViewController:transition: called on <UINavigationController 0x7f984204f800> while an existing transition or presentation is occurring; the navigation stack will not be updated