如何使用Swift 4.2创建searchBar globall搜索可编码JSON数组值?

如何使用Swift 4.2创建searchBar globall搜索可编码JSON数组值?,json,swift,tableview,uisearchbar,Json,Swift,Tableview,Uisearchbar,在我的场景中,我使用可编码结构将JSON数据加载到tableview中。在这里,我试图通过使用故事板添加搜索栏。我不知道如何将self.tableArray数据与搜索栏筛选数组同步。请提供一些想法 我的可编码结构 struct Root: Codable { let data: [Datum] } struct Datum: Codable { let id, userID, country, card: Int let category: Int let ti

在我的场景中,我使用可编码结构将JSON数据加载到tableview中。在这里,我试图通过使用故事板添加搜索栏。我不知道如何将self.tableArray数据与搜索栏筛选数组同步。请提供一些想法

我的可编码结构

struct Root: Codable {
    let data: [Datum]
}

struct Datum: Codable {
    let id, userID, country, card: Int
    let category: Int
    let title, description: String
    let createDate
    let user: User

    enum CodingKeys: String, CodingKey {
        case id
        case userID = "user_id"
        case country, card, category, title, description
        case createDate = "create_date"

    }
}

struct User: Codable {
    let firstname, lastname: String
}
我的JSON代码

do {
          let result = try JSONDecoder().decode(Root.self, from:data!)
          self.tableArray = result.data

} catch {
          print(error)
          self.tableArray = []
}
我的Tableview代码

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return filteredData.count
        return tableArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

      let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! CustomTableViewCell

      let item = tableArray[indexPath.row]
      cell.name_label.text = ("\(item.user.firstname) " + "\(item.user.lastname)")
      cell.date_label.text = item.createDate

       return cell
}
搜索条形码

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // When there is no text, filteredData is the same as the original data
        // When user has entered text into the search box
        // Use the filter method to iterate over all items in the data array
        // For each item, return true if the item should be included and false if the
        // item should NOT be included
        filteredData = searchText.isEmpty ? names : names.filter({(dataString: String) -> Bool in
            // If dataItem matches the searchText, return true to include it
            return dataString.range(of: searchText, options: .caseInsensitive) != nil
        })
        tableView.reloadData()
    }

首先需要授权搜索栏,以便将其添加到UISearchBarDelegate。在这个方法中,有一个函数可以检查搜索栏中的文本是否发生了变化。是的

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { }
但首先需要声明一个变量

var isSearching = false
并添加此函数

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchBar.text == nil || searchBar.text == "" { // 



        isSearching = false
        view.endEditing(true)
        tableView.reloadData()
    }
    else {
        isSearching = true
        newArray = tableArray.filter({ value -> Bool in
            guard let text =  searchBar.text else { return false}
           return value.title.contains(text) // According to title from JSON

        })
        tableView.reloadData()
    }
}
newArray是相同的tableArray,但它是空的

您需要检查als numberOfRowsInSection。若你们不修改,它会给出错误,比如索引超出范围

改变它

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if isSearching {
        return newArray.count
    }
    else {
           return self.tableArray.count
     }




    return 0
}
更新 当前位置我认为问题出在这一部分。您还需要在此处添加isSearching

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

  let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! CustomTableViewCell
   if isSearching{ 
   // Need to change according to newArray
   let item = newArray[indexPath.row]
   cell.name_label.text = ("\(item.user.firstname) " + "\(item.user.lastname)")
  cell.date_label.text = item.createDate

  }
  else {
  let item = tableArray[indexPath.row]
  cell.name_label.text = ("\(item.user.firstname) " + "\(item.user.lastname)")
  cell.date_label.text = item.createDate
  }
   return cell

}

您的问题中根本没有与搜索栏相关的代码。你尝试了什么?搜索条码更新@DávidPásztorThank you@Omer tekbiyikI我收到错误newArray=self.users.name.firstname.filter{value->Bool在我的JSON数组中var users=[User]@Omer TekbiyiknewArray必须像var nemArray=[Post]像tableArray@devmikleI一样,我正在搜索演示名称。我有三个演示列表,但搜索后只有一个显示Tableview而不是重新加载。我给了Tableview.reload,但没有重新加载。请根据您的代码更新您的答案@Omer TekbiyikAs,为我搜索只显示第一个索引。@Omer Tekbiyik