Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use scope bar with UISearchController

I am able to create scope bar to UISearchController & set their titles

    resultSearchController = ({

        let controller = UISearchController(searchResultsController: nil)

        controller.searchResultsUpdater = self

        controller.dimsBackgroundDuringPresentation = false

        controller.searchBar.showsScopeBar = true

        controller.searchBar.scopeButtonTitles = ["One", "two", "three"]

        controller.searchBar.sizeToFit()

        self.tableView.tableHeaderView = controller.searchBar


        return controller

    })()

But how do I actually sort using scope bar. My current sorting method is as follows

func updateSearchResultsForSearchController(searchController: UISearchController) {

    filteredTableData.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)

    let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)

    filteredTableData = array as! [String]

    tableView.reloadData()

}
like image 877
Apoorv Mote Avatar asked May 15 '15 07:05

Apoorv Mote


1 Answers

You need to add search bar delegate as follows.

class NumberTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {

Save register delegate in view did load as follows

resultSearchController.searchBar.delegate = self

Delegate has method to tell you which scope bar button is pressed as follows

    func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

    filterArrayWithCharacterLength(selectedScope)

}

For detailed information check my tutorial on How to add UISearchController to tableView

like image 118
Apoorv Mote Avatar answered Oct 03 '22 06:10

Apoorv Mote