Search bar hides on tap

Viewed 434

Hi I have added search bar on UIView. When i run my code I can see my search bar, but as I tap inside search bar it hides itself, and when i tap again somewhere on screen it is visible.I am not getting this issue now.Please help.

 var searchView:UIView = {
        var search = UIView()
        search.translatesAutoresizingMaskIntoConstraints = false
        search.backgroundColor = UIColor.gray
        return search
    }()

   lazy var searchController : UISearchController = {
        var searchController = UISearchController(searchResultsController: nil)
        //searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.searchBar.barTintColor = UIColor.gray
        searchController.searchBar.layer.borderWidth = 1
        searchController.searchBar.layer.borderColor = UIColor.gray.cgColor
        //searchController.dimsBackgroundDuringPresentation = false
        searchController.definesPresentationContext = true
        searchController.searchBar.sizeToFit()
        searchController.searchBar.translatesAutoresizingMaskIntoConstraints = false
        return searchController
    }()
func setUpView(){
    view.addSubview(searchView)
    searchView.addSubview(searchController.searchBar)

    searchView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    searchView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    searchView.topAnchor.constraint(equalTo: view.topAnchor,constant:64).isActive = true
    searchView.heightAnchor.constraint(equalToConstant: 65).isActive = true

    searchController.searchBar.leftAnchor.constraint(equalTo: searchView.leftAnchor).isActive = true
    searchController.searchBar.rightAnchor.constraint(equalTo: searchView.rightAnchor).isActive = true
    searchController.searchBar.topAnchor.constraint(equalTo: searchView.topAnchor,constant:10).isActive = true
    searchController.searchBar.widthAnchor.constraint(equalTo: searchView.widthAnchor).isActive = true
    }

Also I have given this line in ViewDidLoad()-:

self.extendedLayoutIncludesOpaqueBars = true
1 Answers

I found that UISearchController's searchBar doesn't work well when it's set translatesAutoresizingMaskIntoConstraints = false. As a workaround, I embedded the search bar into a placeholder view with the desired constraints:

let searchBarPlaceholderView = UIView()
searchBarPlaceholderView.addSubview(searchController.searchBar)
searchBarPlaceholderView.translatesAutoresizingMaskIntoConstraints = false
searchBarPlaceholderView.heightAnchor.constraint(equalToConstant: 56).isActive = true
stackView.addArrangedSubview(searchBarPlaceholderView)

Notice, that the searchController.searchBar's translatesAutoresizingMaskIntoConstraints property is left true.

Related