4
votes

I'm experimenting with the new UISearchController API introduced in iOS 8. Although the API is new, it uses the same old UISearchBar. I added it to the UINavigationController's titleView.

enter image description hereenter image description here

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchController = UISearchController(searchResultsController: nil)
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.delegate = self
        navigationItem.titleView = searchController.searchBar
    }
}

I don't need the search bar to take the entire width of the navigation bar. The problem is I can't resize it. First I tried setting the search bar's frame.

searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 100, height: 44)

That didn't work so I tried setting the titleView's frame.

navigationItem.titleView!.frame = CGRect(x: 0, y: 0, width: 100, height: 44)

Neither of them works.

Does anyone know another way to do this?

Thank you.

1

1 Answers

15
votes

You can use another view as navigation bar title and place search bar inside it. If bar tint color problem occurs, it can be solved by setting backgroundImage property. This should work:

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

let frame = CGRect(x: 0, y: 0, width: 100, height: 44)
let titleView = UIView(frame: frame)
searchController.searchBar.backgroundImage = UIImage()
searchController.searchBar.frame = frame
titleView.addSubview(searchController.searchBar)
navigationItem.titleView = titleView