SearchBar not showing up in NavigationBar in Swift 4 IOS 11

Viewed 4102

I have been trying to add Searchbar via UISearchController in my app. It does not show up on my navigation bar.I have added a navigation controller as a root view controller and have not changed anything but just the tint colour of it. I have tried few solutions but nothing works. I am using Swift 4.0 with Xcode 9 and running the app on IOS 11. Below is my code. Thanks in advance.

if #available(iOS 11.0, *) {
        let sc = UISearchController(searchResultsController: nil)
        sc.delegate = self
        let scb = sc.searchBar
        scb.sizeToFit()

        scb.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
        scb.tintColor = UIColor.white


        self.navigationController?.navigationItem.searchController = sc
        self.navigationController?.navigationItem.hidesSearchBarWhenScrolling = false

    }
3 Answers

I don't know why but it will help you.

Add search controller in NavigationItem directly.

navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false

Set the searchbar as your tableview header, worked for me.

self.tableView.tableHeaderView = self.searchController.searchBar

Maybe delete sc.delegate = self and put instead scb.delegate = self. Also, I think you have to choose only one between scb.sizeToFit() and scb.heightAnchor.constraint(equalToConstant: 44.0).isActive = true because one excludes the other one. Hope it helps.

Related