Peter Pik Peter Pik - 22 days ago 6
iOS Question

adding searchBar to navigationBar in swift

i'm trying to add a searchBar to the navigationBar. i've researched a bit and this is what i've done so far:

The problem is nothing appear to the navigationBar using this code.

searchBar = UISearchBar(frame: CGRectMake(0, 0, 320, 44))
searchBar?.delegate = self
searchBar?.showsCancelButton = true


searchController = UISearchDisplayController()
searchController?.delegate = self
searchController?.searchResultsDelegate = self

searchController?.displaysSearchBarInNavigationBar = true

Answer

Try this code that worked for me:

 lazy   var searchBars:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 200, 20))

override func viewDidLoad() {
    super.viewDidLoad()
    var leftNavBarButton = UIBarButtonItem(customView: searchBars)
    self.navigationItem.leftBarButtonItem = leftNavBarButton
}