How do you hide a SearchController or make it smaller?

59 views Asked by At

I have a SearchController with a search bar that is currently hidden. I do not need the user to be able to type in it. As you can see, there is a blank space where the searchBar would be:

SearchController

Is there a way to also hide this? Or to make it smaller or reposition it?

This is how I set up the searchController:

override func viewDidLoad() {
    initSearchController()
}

let searchController = UISearchController()
let searchBar = UISearchBar()

func initSearchController() {
    
    searchController.loadViewIfNeeded()
    searchController.searchResultsUpdater = self
    navigationItem.searchController = searchController
    
    searchController.definesPresentationContext = true
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.enablesReturnKeyAutomatically = false
    searchController.searchBar.returnKeyType = UIReturnKeyType.done
    navigationItem.hidesSearchBarWhenScrolling = false
    
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.isHidden = true

    searchController.searchBar.becomeFirstResponder()
}
1

There are 1 answers

1
Sreekuttan On

You only need to set the searchController if needed.

    let searchController = UISearchController()
    
    var hideSearchBar: Bool = true {
        didSet {
            navigationItem.searchController = hideSearchBar ? nil : searchController
        }
    }
   
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        initSearchController()
        hideSearchBar = false
        
    }
    
    func initSearchController() {
        
        searchController.loadViewIfNeeded()
        searchController.searchResultsUpdater = self
        
        searchController.definesPresentationContext = true
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.enablesReturnKeyAutomatically = false
        searchController.searchBar.returnKeyType = UIReturnKeyType.done
        navigationItem.hidesSearchBarWhenScrolling = false
        
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.searchBar.becomeFirstResponder()
    }

    @IBAction func toggleSearch(_ sender: Any) {
        hideSearchBar.toggle()
    }