iOS 13如何在NavigationBar中隐藏UISearchController searchBar

Mic*_*bro 5 ios swift uisearchcontroller ios13

我有带有搜索栏(UISearchController)的导航栏,还有左栏按钮图标,单击该图标时,通过将其分配给navigationItem来显示此搜索控制器,如下所示:

if navigationItem.searchController != nil {
            navigationItem.searchController = nil
            navigationController?.view.setNeedsLayout()
            navigationController?.view.layoutIfNeeded()
        } else {
            navigationItem.searchController = searchController
            navigationController?.view.setNeedsLayout()
            navigationController?.view.layoutIfNeeded()

            searchController.searchBar.becomeFirstResponder()
        }
Run Code Online (Sandbox Code Playgroud)

它有效,但是如果在“取消”按钮上触摸,我尝试隐藏搜索栏,则关闭了视图控制器,并出现黑屏(无视图控制器)

extension SearchableMenuViewController : UISearchBarDelegate {

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        guard #available(iOS 11.0, *) else { return }
        guard !isAlwaysVisible else { return }

        if #available(iOS 13.0, *) {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.navigationItem.searchController = nil
                self.navigationController?.view.setNeedsLayout()
                self.navigationController?.view.layoutIfNeeded()
            }
        } else {
            navigationItem.searchController = nil
            navigationController?.view.setNeedsLayout()
            navigationController?.view.layoutIfNeeded()
        }
    }
Run Code Online (Sandbox Code Playgroud)

我试图添加延迟原因,原因是没有从NavigationItem中删除此searchcontroller,而是使用Title + Search Controller将其动画化为扩展的导航栏,然后点击Search icon正确隐藏了搜索控制器。所以问题是我认为在动画扩展到导航栏时删除搜索控制器

f0r*_*0rz 4

超级蹩脚的 haxx 将暂时解决你的问题:

func didDismissSearchController(_ searchController: UISearchController) {

        if #available(iOS 13, *) {
            navigationItem.searchController = nil

            self.navigationController?.view.setNeedsLayout()
            self.navigationController?.view.layoutSubviews()

            let view = UIView()
            self.navigationController?.navigationBar.insertSubview(view, at: 1)
            view.removeFromSuperview()
        }      
    }
Run Code Online (Sandbox Code Playgroud)