Search code examples
iosswiftipaduikituisearchcontroller

How to add a search bar to the navigation bar


I'd love to add a search bar managed by UISearchController to the right side of my navigation bar.

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    searchController.searchBar.placeholder = "Search"
    searchController.searchBar.searchBarStyle = .Minimal
    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200.0, height: 44.0)
    searchController.hidesNavigationBarDuringPresentation = false
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchController.searchBar)

When I tap on the search bar (so it becomes active) it covers the whole navigation bar (while overlapping everything else) instead of the little part. How can I fix its frame?


Solution

  • Wrapping the search bar in a UIView seems to do the trick.

        searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200.0, height: 44.0)
        let barContainer = UIView(frame: searchController.searchBar.frame)
        barContainer.backgroundColor = UIColor.clearColor()
        barContainer.addSubview(searchController.searchBar)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: barContainer)