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 storyboardjust 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
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)