Search code examples
iosuinavigationcontrolleruikituisearchbaruinavigationitem

UISearchBar in UINavigationController


I am wondering to programmatically put a UISearchBar into UINavigationController, rather than replacing UINavBar title, as I want the large title to show up. See Files app on iOS.

enter image description here


Here is my .swift

class Search: UITableViewController, UISearchBarDelegate

override func viewDidLoad() {
    super.viewDidLoad()
    searchBar()
}

func searchBar() {
    let searchController = UISearchController(searchResultsController: nil)
    navigationItem.searchController = searchController
    navigationItem.searchController?.searchBar.placeholder = "search".localized
    navigationItem.searchController?.dimsBackgroundDuringPresentation = false
    navigationItem.hidesSearchBarWhenScrolling = false
}


The point is: by changing nil to actual searchResultsController, after typing text into search bar, the whole navigation controller (with search bar and typed text) got replaced by the searchResultsController view. No search bar while typing into it in short.

I am trying hard to use iOS 11/12 native look and feel within the app and putting the search bar into TableViewController is a no way here. Can someone help me?


Solution

  • If you don't need a different view controller to display the results simply use (it will not make your navigation bar disappear):

    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self
    

    And do not change the value after that.

    Most of your code is good, however you will need to implement the UISearchResultsUpdating protocol to detect updates (when the user write in the search bar) and use a table view (inside your view controller) to display the results of the search. You do that by reloading the data of your table view inside the function: updateSearchResults(for searchController:) after filtering the data you want with the text inside the search bar. You can read this good tutorial on the subject for more information.