Add filter button to UISearchController

smnk picture smnk · Jan 27, 2016 · Viewed 8.7k times · Source

I want to add a "filter" or "sort" button next to the searchBar inside a UISearchController. I have already tried to add the UIButton and the searchbar into a UIView and set this as my UITableView tableView.tableHeaderView This does not work because the tableView.tableHeaderView get's set back to the UISearchBar only when dismissing the controller. Here is an example of how I want it to look:enter image description here

Answer

Ali Mert Özdemir picture Ali Mert Özdemir · Jun 19, 2017

I could create a search filter with a few lines of code. I hope it helps.

*I chose the bookmark button to apply filter icon; because I have already used cancel button for custom action.

First, you have to delegate searchBar to handle bookmark button click action. Then you should set properties as below. If you want to give custom position (default position is right side), you need to setPositionAdjustment.

searchController.searchBar.delegate = self
searchController.searchBar.showsBookmarkButton = true
searchController.searchBar.setImage(UIImage(named: "Sort"), for: .bookmark, state: .normal)
// MARK: You may change position of bookmark button.
//searchController.searchBar.setPositionAdjustment(UIOffset(horizontal: 0, vertical: 0), for: .bookmark)

Then, override searchBarBookmarkButtonClicked function inside your VC. You can handle click event inside this method.

func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) { //showAlert, presentVC or whatever you want here }

Also if you want to hide bookmark button while search controller is active, you need to apply control inside updateSearchResults method.

if searchController.isActive {
    searchController.searchBar.showsBookmarkButton = false
} else {
    searchController.searchBar.showsBookmarkButton = true
}


When searchController is not active:

While searchController is not active


When searchController is active:

searchController is active