Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put UISearchController Searchbar onto navigation bar with code

Tags:

xcode

ios

swift

If I embed the ViewController into a Navigation Bar, navigationItem.titleView.resultSearchController?.searchBar will put a search bar into the navigation bar. However, I've created a UISearchController and a UINavigationBar with code. This time, the navBar is showing up, but the searchBar isn't.

resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable

let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.delegate = self

let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y:0, width: 375, height: 64))
self.view.addSubview(navBar)
//navBar.topItem = resultSearchController?.searchBar
self.navigationItem.titleView = resultSearchController?.searchBar

navBar.topItem = resultSearchController?.searchBar doesn't work because topItem is a String value and resultSearchController?.searchBar is a UIView type. How can I achieve the same effect?

like image 584
zachenn Avatar asked Mar 09 '23 07:03

zachenn


1 Answers

Create a UINavigationItem instance and add it to the created navigation bar. Add the search controller search bar to the UINavigationItem as titleView.

class SearchViewController: UIViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {

    var searchController: UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addNavigationbar()
    }

    func addNavigationbar() {
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 60))
        self.view.addSubview(navBar)

        let navigationItem = UINavigationItem(title: "")
        self.searchController = searchControllerWith(searchResultsController: nil)
        navigationItem.titleView = self.searchController.searchBar

        navBar.setItems([navigationItem], animated: false)
        self.definesPresentationContext = true
    }

    func searchControllerWith(searchResultsController: UIViewController?) -> UISearchController {

        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.delegate = self
        searchController.searchResultsUpdater = self
        searchController.searchBar.delegate = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = true

        return searchController
    }
like image 138
Anand Menon Avatar answered Apr 09 '23 02:04

Anand Menon