Get search bar in navigation bar in Swift

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


    // 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

Swift 5, XCode 11, Storyboard way so you can easily add all the search bar attributes through the storyboard and you have less code in your view controller class.

1.) Add your search bar view as external view in viewcontroller.

enter image description here

2.) Connect searchBarView to you viewcontroller.

enter image description here

3.) Add your searchBarView to your navigationBar title item.

navigationItem.titleView = searchBarView

Result:

enter image description here


In your view controller:

lazy var searchBar = UISearchBar(frame: CGRectZero)

override func viewDidLoad() {
    super.viewDidLoad()

    searchBar.placeholder = "Search"

    navigationItem.titleView = searchBar
}

Doing it this way, by setting the navigationItem.titleView, the search bar is automatically centered across the iPhone and iPad devices. Note: only tested with v8.4 and v9.0

for SWIFT 3

lazy var searchBar = UISearchBar(frame: CGRect.zero)