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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With