我已经解析了一个 JSON 数组,它为我提供了 [[String:String]]
,然后我将其放入 TableView 中。
我想使用 UISearchBar
来搜索数据,但遇到了麻烦,因为我不确定如何处理 [[String:String]]
格式。
我已经尝试创建另一个变量,它将数组数据保存为 [String]
并且我可以过滤它,但我无法正确显示结果。抱歉,如果这有点令人困惑,因为我在过去几个小时试图弄清楚这一点时感到困惑。谢谢!
import UIKit
import Alamofire
import SwiftyJSON
class StartViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
var names = [
[String: String]
]()
var isSearching = false
var filteredData = [String]()
@IBOutlet weak
var tableView: UITableView!
@IBOutlet weak
var searchBar: UISearchBar!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath)
let name = names[indexPath.row]
let text: String!
// here I get 'Cannot assign value of type '[String : String]' to type 'String?''
if isSearching {
text = filteredData[indexPath.row]
} else {
text = nil
}
cell.textLabel ? .text = name["name"]
cell.textLabel ? .textColor = UIColor.blue
return cell
}
}
这里有两个部分
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
// and here I get 'Binary operator '==' cannot be applied to operands of type '[String : String]' and 'String?''
filteredData = names.filter({
$0 == searchBar.text
})
tableView.reloadData()
}
}
感谢您的帮助。
编辑: //这是我的解析函数,如果有帮助的话
func parse(json: JSON) {
for result in json[].arrayValue {
let name = result["name"].stringValue
let obj = ["name": name]
names.append(obj)
}
tableView.reloadData()
}
最佳答案
为了能够显示完整数据和过滤后的数据,两个数组的类型必须相同。
var filteredData = [[String:String]]()
在cellForRow
中使用依赖于isSearching
的数组
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath)
let text : [String:String]
if isSearching {
text = filteredData[indexPath.row]
} else {
text = names[indexPath.row]
}
cell.textLabel?.text = text["name"]
cell.textLabel?.textColor = UIColor.blue
return cell
}
例如,在 searchBar:searchDidChange
中,您必须按键过滤
filteredData = names.filter({
$0["name"] == searchBar.text
})
但是我建议使用自定义类或结构而不是字典。
关于ios - 如何过滤 [[String :String]] using UISearchBar and display as String 类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51285725/