Search code examples
iosswiftswift3uisearchbaruisearchcontroller

How to implement scopeButtonTitles for a customized UISearchBar?


I have a customized UISearchBar, when an user click on the searchBar, I want to show an additional buttons. So, I'm using scopeButtonTitles property to display the additional buttons. But, it's not appearing on the UISearchBar.

customSearchController = CustomSearchController(searchResultsController: self, searchBarFrame: CGRect(x: 0.0, y: 0.0, width: tableView.frame.size.width, height: 50.0), searchBarFont:  UIFont.systemFont(ofSize: 16.0),                                                             searchBarTextColor: UIColor.white, searchBarTintColor: UIColor.primaryBlue())
customSearchController.hidesNavigationBarDuringPresentation = false
customSearchController.dimsBackgroundDuringPresentation = false
customSearchController.customSearchBar.placeholder = NSLocalizedString("Search", comment: "Search")
customSearchController.customSearchBar.accessibilityLabel = customSearchController.searchBar.placeholder
//Scope Buttons
customSearchController.customSearchBar.scopeButtonTitles = [NSLocalizedString("List", comment: "List"), NSLocalizedString("Map", comment: "Map")]

If I'm not using customize UISearchBar, it's working fine. the actual problem is when I'm going for customize UISearchBar.


Solution

  • Set the showsScopeBar property of UISearchBar to true to the show the scopeBar.

    customSearchController.customSearchBar.showsScopeBar = true
    

    Edit: For that you can use delegate method searchBarTextDidBeginEditing and show the scopebar.

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        customSearchController.customSearchBar.showsScopeBar = true
        //set the frame so it will show scope bar properly.
    }
    

    Now if you want to hide the scoprBar after search then you can use searchBarCancelButtonClicked to hide the scope bar.

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        customSearchController.customSearchBar.showsScopeBar = false
        //set the frame again
    }