【问题标题】:UISearchBar Filter UITableView with NSPredicate filter from array of dictionary with multiple KeysUISearchBar Filter UITableView with NSPredicate filter from the array of dictionary with multiple Keys
【发布时间】:2019-07-10 10:53:02
【问题描述】:

我正在UITableView 上设置UISearchBarUITableViewCell 有 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()
    }
}

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

【问题讨论】:

  • 你能用例子解释一下你的预期结果吗
  • let keys = ["name", "phone", "email"]; let subPredicates = keys.map({ NSPredicate(format: "%K CONTAINS[c] %@", $0, searchText) }); let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: subPredicates)?但是为什么要使用 NSPredicate?为什么不直接使用filter({}) 还有,为什么使用NSArray
  • 好的,我把它改成 Array 尝试通过过滤器使用,但无法做到
  • @Asif 结果应该是在搜索栏中搜索到的文本
  • 您的cleanerList 的类型是什么? [[字符串:字符串]]? Larme 的谓词解决了您的问题,但您可以使用filter({}) 更轻松地做到这一点,就像上面所说的

标签: swift uitableview uisearchbar nspredicate


【解决方案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()
    }
}

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 2022-12-27
    • 2022-12-02
    • 1970-01-01
    • 2022-11-24
    • 2015-12-31
    • 2022-12-01
    • 2022-12-01
    相关资源
    最近更新 更多