adding searchBar to navigationBar in swift
11,688
Solution 1
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
}
Solution 2
Try this
lazy var searchBar = UISearchBar(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = searchBar}
Solution 3
You can use this
private let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
}
Author by
Peter Pik
Updated on June 20, 2022Comments
-
Peter Pik almost 2 years
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