键入时搜索栏从视图中消失

Search Bar disappeared from view while typing

我在 ViewDidLoad() 中将 SearchBar 添加到我的 TableView 中:

    self.searchBar = UISearchController(searchResultsController: nil)
    self.searchBar.searchResultsUpdater = self

    self.searchBar.dimsBackgroundDuringPresentation = false
    self.searchBar.searchBar.sizeToFit()

    self.tableView.tableHeaderView = self.searchBar.searchBar
    self.tableView.reloadData()

一切正常,但是当我点击这个 SearchBar 它消失了。这意味着,我仍然可以打字,我可以看到结果,但是看不到 SearchBar。我实现了 UISearchBarDelegate 并且我一直在尝试添加

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    self.navigationController?.navigationBarHidden = false
}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    self.navigationController?.navigationBarHidden = true
}

但还是不行。你知道为什么这个 Search Bar 消失了吗?

这个问题的解决方案是(就像@sandy sad)在viewDidLoad()

中写下这行代码
 self.aNavigationController?.extendedLayoutIncludesOpaqueBars = true

但现在我遇到了一个新问题,这意味着当我在 TableView 中 select 行并显示新的 VievController 时,SearchBar 没有消失,我看到了在新的视野中。为什么?

其实search Bar并没有隐藏,只是根据文字调整了widthheight

Remove this line from your code and it will work fine.

self.searchBar.searchBar.sizeToFit()

您需要在 viewDidLoad() 中将 extendedLayoutIncludesOpaqueBars 设置为 true。

self.aNavigationController?.extendedLayoutIncludesOpaqueBars = true