【问题标题】:How do I filter data from database arrays using Search bar如何使用搜索栏从数据库数组中过滤数据
【发布时间】:2020-01-08 02:04:29
【问题描述】:

我使用搜索栏过滤数据库中的数据并将填充 tableView。我在 isSearching 部分遇到错误。

Value of type 'DataSnapshot' has no member 'contains'

代码如下。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        isSearching = false
        view.endEditing(true)
        tableView.reloadData()
    } else {
        isSearching = true
        filteredColorRequests = colors.filter{$0.contains(searchBar.text!)}
        tableView.reloadData()
    }
}

如何

【问题讨论】:

    标签: xcode search filter


    【解决方案1】:

    您当然想搜索特定的String 属性,例如name

    使用 searchText 参数而不是从栏获取搜索字符串,该参数已经是非可选的。

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty {
            isSearching = false
            view.endEditing(true)
        } else {
            isSearching = true
            filteredColorRequests = colors.filter{(($0.value as! [String:Any])["name"] as! String).contains(searchText)}
        }
        tableView.reloadData()
    }
    

    【讨论】:

    • 嗨@vadian。当我尝试输入内容时,它不显示任何内容。我已经更新了 cellForRowAt
    • name 只是一个占位符。我不知道快照包含什么。
    • 它的工作@vadian。谢谢!我还有一个问题。您使用什么代码来过滤与当前用户的距离。就像我想在列表上显示离最远的最近的人。我有我的快照用户经度和纬度。
    • 使用CoreLocation的API。从纬度/经度创建CLLocation 对象并计算两个位置之间的距离很容易。
    • .range(of: searchText, options: .caseInsensitive) != nil替换.contains(searchText)
    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-12-12
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多