Peter Pik
Peter Pik

Reputation: 11193

adding searchBar to navigationBar in swift

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

Upvotes: 6

Views: 13041

Answers (3)

Dmih
Dmih

Reputation: 636

You can use this

private let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {

 self.navigationItem.searchController = searchController
 self.navigationItem.hidesSearchBarWhenScrolling = false
}

Upvotes: 4

Chinju James
Chinju James

Reputation: 201

Try this

lazy var searchBar = UISearchBar(frame: .zero)
override func viewDidLoad() {
    super.viewDidLoad()
 navigationItem.titleView = searchBar} 

Upvotes: 4

Constantin Suiu
Constantin Suiu

Reputation: 246

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
}

Upvotes: 7

Related Questions