Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get search bar in navigation bar in Swift

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?

like image 699
idris Avatar asked Nov 04 '14 01:11

idris


People also ask

How do I add a search bar to UITableView?

Adding Search Bar on TableViewAdd the UISearchBar at the top of your UITableView. … and give the name searchBar. In the ViewController add a Boolean called searching to know when to switch between the full list of items and the list of items from the searching results.

How do I customize the search bar in Swift?

Change Search Bar Default Image Color The left hand default search image in UISearchBar represents the left view of the UITextField. The Image is rendered to change it to the desired colour. @IBOutlet weak var searchBar: UISearchBar! Hope it will help you in customising the UISearchBar in your app.


2 Answers

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

like image 131
Leo Avatar answered Sep 18 '22 10:09

Leo


    // create the search bar programatically since you won't be     // able to drag one onto the navigation bar     searchBar = UISearchBar()     searchBar.sizeToFit()      // the UIViewController comes with a navigationItem property     // this will automatically be initialized for you if when the     // view controller is added to a navigation controller's stack     // you just need to set the titleView to be the search bar     navigationItem.titleView = searchBar 
like image 42
antonio081014 Avatar answered Sep 22 '22 10:09

antonio081014