The width of the UISearchBar does not change when it is embedded in the UINavigationBar

I am experimenting with the new UISearchControllerAPI introduced in iOS 8. Although the API is new, it uses the same old one UISearchBar. I added it to UINavigationController 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 a search bar to take the full width of the navigation bar. The problem is that I cannot resize it. At first I tried to set the frame of the search bar.

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

This did not work, so I tried to set the frame titleView.

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

None of them work.

Does anyone know another way to do this?

Thank.

+4
source share
1 answer

. , , backgroundImage. :

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
+14

All Articles