Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SearchBar not showing up in NavigationBar in Swift 4 IOS 11

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

    }
like image 738
Achilles Avatar asked Nov 27 '17 05:11

Achilles


2 Answers

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

Add search controller in NavigationItem directly.

navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false
like image 59
Jay Patel Avatar answered Nov 08 '22 22:11

Jay Patel


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

self.tableView.tableHeaderView = self.searchController.searchBar
like image 38
itsmcgh Avatar answered Nov 08 '22 23:11

itsmcgh