如何使用UISearchBar过滤类型]的数组并显示为String
我已经解析了一个JSON数组,它给了我[[String:String]]
然后我把它放到一个表视图中。
我想使用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() } }
谢谢您的帮助。
编辑://这是我的解析function,如果这有帮助的话
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 })
但是我建议使用自定义类或结构而不是字典。