Get search bar in navigation bar in Swift

user302975 picture user302975 · Nov 4, 2014 · Viewed 75k times · Source

So I've tried everything trying to get a search bar into the navigation bar in Swift. But sadly I haven't gotten it working, just yet...

For those of you who don't know what I'm talking about, I'm trying to do something like this

enter image description here

Note the search bar in the navigation bar. So here's what I'm currently using

self.searchDisplayController?.displaysSearchBarInNavigationBar = true

I popped that in my viewDidLoad, and then when I load up the app I'm presented with, just an empty navigation bar.... :( Any ideas?

Answer

Leo picture Leo · Nov 4, 2014

Try this

let leftNavBarButton = UIBarButtonItem(customView:Yoursearchbar)
  self.navigationItem.leftBarButtonItem = leftNavBarButton

Update

You keep a lazy UISearchBar property

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

In viewDidLoad

searchBar.placeholder = "Your placeholder"
var leftNavBarButton = UIBarButtonItem(customView:searchBar)
self.navigationItem.leftBarButtonItem = leftNavBarButton

If you want to use storyboard just drag your searchbar as a outlet,then replace the lazy property with your outlet searchbar