如何在swift 3 tableview中过滤多维数组

时间:2017-07-11 07:06:33

标签: ios swift swift3

如果我在UISearchBar中使用简单数组,它运行正常。

但是当我在Multidimensional Array中使用UISearchBar时,它无效。

我的代码如下:

 class ViewController: UIViewController  ,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate{

  @IBOutlet weak var seachBar: UISearchBar!

  @IBOutlet weak var tableView: UITableView!

  var serachingArray = [[String:AnyObject]]();
  var seraching:Bool = false
   var originalArray = [
    ["name":"Enamul Haque" as AnyObject ,"address":"28 top kana" as AnyObject],
    ["name":"Raque" as AnyObject ,"address":"39 Alo kana" as AnyObject],
    ["name":"Enamul" as AnyObject ,"address":"D/28 kana" as AnyObject]
]


 override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    seachBar.delegate = self

 }


 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     if(seraching == true){
        return serachingArray.count
      }else{
         return originalArray.count
      }
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
      if(seraching == true){
        cell.tv_name.text =  serachingArray[indexPath.row]["name"] as! String
      }else{
         cell.tv_name.text =  originalArray[indexPath.row]["name"] as! String

     }
    return cell
}

  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
      print("searchText",searchText)
       serachingArray = originalArray.filter({ (text) -> Bool in
        let temp:NSString = text as! NSString
        var range = temp.range(of: searchText,options:NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound

    })

       if(serachingArray.count == 0){
          seraching = false
      }else{
         seraching = true
       }
        self.tableView.reloadData();
      }
 }

如何将原始数组分配给搜索数组? 请建议。

2 个答案:

答案 0 :(得分:1)

试试这个: -

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print("searchText",searchText)
        serachingArray = self.originalArray.filter({(($0["name"] as! String).localizedCaseInsensitiveContains(searchText))!})

        if(serachingArray.count == 0){
            seraching = false
        }else{
            seraching = true
        }
        self.tableView.reloadData();
}

答案 1 :(得分:0)

尝试用给定代码替换textDidChange代码

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
   serachingArray = originalArray.filter {
      return $0["name"]!.caseInsensitiveCompare(searchText) == .orderedSame
   }
   ... remaining code
}

将originalArray值更改为字符串如果使用swift,则无需将它们声明为AnyObject

var originalArray = [
    ["name":"Enamul Haque","address":"28 top kana"],
    ["name":"Raque","address":"39 Alo kana"],
    ["name":"Enamul","address":"D/28 kana"]
]

var serachingArray = [[String: Any]]()