如何在范围按钮更改时更新搜索结果。 Swift UISearchController

How to update search results when scope button changed. Swift UISearchController

如何在范围按钮发生变化时更新搜索结果(在我点击范围之后)? 当我再次输入时,搜索结果发生了变化(具有新的范围)!

searchControl - 配置 导入 UIKit

class ProductTableView: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating
{

    @IBOutlet weak var tableView: UITableView!
    var searchController: UISearchController!

    var friendsArray = [FriendItem]()
    var filteredFriends = [FriendItem]()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        searchController = UISearchController(searchResultsController: nil)
        searchController.searchBar.sizeToFit()
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        searchController.searchBar.scopeButtonTitles = ["Title","SubTitle"]
        definesPresentationContext = true
        tableView.tableHeaderView = searchController.searchBar

        self.tableView.reloadData()


    }

更新功能 当我键入文本时,NSLog 打印我的文本和范围编号。 当我改变范围时 - 什么都没有!!!

func updateSearchResultsForSearchController(searchController: UISearchController) {
    let searchText = searchController.searchBar.text
    let scope = searchController.searchBar.selectedScopeButtonIndex
    NSLog("searchText - \(searchText)")
    NSLog("scope - \(scope)")
    filterContents(searchText, scope: scope)
    tableView.reloadData()
}

过滤功能

func filterContents(searchText: String, scope: Int)
    {

        self.filteredFriends = self.friendsArray.filter({( friend : FriendItem) -> Bool in
    var fieldToSearch: String?
            switch (scope){
            case (0):
                fieldToSearch = friend.title
            case(1):
                fieldToSearch = friend.subtitle
            default:
                fieldToSearch = nil
            }

            var stringMatch = fieldToSearch!.lowercaseString.rangeOfString(searchText.lowercaseString)
            return stringMatch != nil

        })
    }

请帮帮我!

您期望的行为是合乎逻辑的,表面上看起来是正确的,但实际上并非如此。值得庆幸的是,有一个简单的解决方法。

Apple 对此方法的描述如下:

Called when the search bar becomes the first responder or when the user makes changes inside the search bar.

范围更改是搜索栏中的更改,对吗?我感觉合理。但是,如果您阅读 讨论 ,Apple 会明确表示该行为不是您所期望的:

This method is automatically called whenever the search bar becomes the first responder or changes are made to the text in the search bar.

不包括在其中:范围的更改。奇怪的事情被忽略了,不是吗?要么在范围更改时调用该方法,要么摘要应该清楚它不是。

您可以通过将 UISearchBarDelegate 协议添加到您的视图控制器并设置 searchController.searchBar.delegate 到您的视图控制器来获得您想要的行为。

然后添加:

func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
    updateSearchResultsForSearchController(searchController)
}

这将导致 updateSearchResultsForSearchController 在作用域发生变化时触发,如您所料。但是相反,您可能希望将 updateSearchResultsForSearchController 的内容分解为 updateSearchResultsForSearchControllerselectedScopeButtonIndexDidChange 都调用的新方法。