UISearchBar筛选器,带有带有多个键的字典数组的NSPredicate筛选器的UITableView

时间:2019-07-10 10:53:02

标签: swift uitableview uisearchbar nspredicate

我正在UISearchBar上设置UITableViewUITableViewCell有3个UIlabel,数据在NSArray中,其中包含三个键"name", "phone", "email"的字典 我已经过滤了表格,但是按名称,电子邮件或电话过滤了 我想用所有三个键进行过滤

尝试了所有NSCoumpound谓词,但失败了 尝试过的过滤器

extension CleanerListViewController: UISearchBarDelegate{
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let formatString = "(name contains[c] %@)"
        filterList = cleanerList.filter { NSPredicate(format: formatString, searchText).evaluate(with: $0) } as NSArray

        if searchText.count == 0{
            filterList = cleanerList
        }
        self.tblCleanerList.reloadData()
    }
}

Github Issue

以上唯一的代码适用于单键 任何帮助将不胜感激,请不要投反对票

1 个答案:

答案 0 :(得分:1)

extension CleanerListViewController: UISearchBarDelegate{
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchText.isEmpty {
            filterList = cleanerList
        } else {
            let keys = ["name", "phone", "email"]
            let subPredicates = keys.map({ NSPredicate(format: "%K CONTAINS[c] %@", $0, searchText) })
            let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: subPredicates)
            filterList = cleanerList.filter { predicate.evaluate(with: $0) } as NSArray
        }

        self.tblCleanerList.reloadData()
    }
}