Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 13 How to hide UISearchController searchBar in navigationBar

I have navigation bar with search bar (UISearchController) I have left bar button icon that when clicked shows this search controller by assigning it to navigationItem like so:

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()
        }

It works but then if on cancel button touch I try to hide search bar then I have view controller dismissed and black screen appears (no view controllers)

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()
        }
    }

I have tried to add delay cause not removing this searchcontroller from navigationItem animates it to extended navigation bar with Title + Search Controller and then tapping Search icon properly hides search controller. So the problem is I think removing search controller while it is animating to extended navigation bar

like image 312
Michał Ziobro Avatar asked Oct 16 '22 11:10

Michał Ziobro


1 Answers

Super lame haxx that will solve your issue temporarily:

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()
        }      
    }
like image 158
f0rz Avatar answered Oct 19 '22 04:10

f0rz