如何在UISearchController中使用范围栏

Apo*_*ote 7 uitableview ios swift uisearchcontroller

我能够为UISearchController创建范围栏并设置它们的标题

    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

    })()
Run Code Online (Sandbox Code Playgroud)

但是我如何使用范围栏进行实际排序.我目前的排序方法如下

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()

}
Run Code Online (Sandbox Code Playgroud)

Apo*_*ote 1

您需要添加搜索栏委托,如下所示。

class NumberTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
Run Code Online (Sandbox Code Playgroud)

在视图中保存注册委托确实加载如下

resultSearchController.searchBar.delegate = self
Run Code Online (Sandbox Code Playgroud)

委托有方法告诉您按下了哪个范围栏按钮,如下所示

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

    filterArrayWithCharacterLength(selectedScope)

}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看我的教程:如何将 UISearchController 添加到 tableView