首页 > 解决方案 > 如何在swift iOS应用程序中使用JSON解码器实现UISearchBar以过滤名称或大写JSON

问题描述

如何在 swift iOS 应用程序中使用 JSON 解码器实现 UISearchBar 以过滤名称或大写 JSON。我想使用 JSON 数据中的名称实现 UISearchBar 和搜索结果或过滤结果。

  import UIKit

创建的结构

  struct jsonstruct:Decodable
  {
  let name:String   
   let capital:String
  }

  class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate, UISearchControllerDelegate, UISearchDisplayDelegate {

为 TableView 和 SearchBar 创建 Outlet

   @IBOutlet var tableview: UITableView!

   @IBOutlet var searchBar: UISearchBar!

声明 JSON

   var arrdata = [jsonstruct]()

获取数据的函数

func getdata()
{
let url = URL(string: "https://restcountries.eu/rest/v2/all")

URLSession.shared.dataTask(with: url!)
{
(data, response, error) in

do
{
if error == nil
{
self.arrdata = try
JSONDecoder().decode([jsonstruct].self, from: data!)

for mainarr in self.arrdata
{
print(mainarr.name,":",mainarr.capital as Any)
DispatchQueue.main.async 
{
self.tableview.reloadData()
}
}
}
}
catch
{
print(error.localizedDescription)
}
}.resume()
}

表视图

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{
return self.arrdata.count
}

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

let cell:TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.label1.text = "Name: \(arrdata[indexPath.row].name)"
cell.label2.text = "Capital: \(arrdata[indexPath.row].capital)"
return cell
}

覆盖函数

override func viewDidLoad() 
{
getdata()
}

标签: iosjsonswiftuisearchbarsearchbar

解决方案


您需要制作两个数据对象,一个是原始数据,另一个是过滤后的数据。

var filteredArrData = [jsonstruct]()
var arrdata = [jsonstruct]()

比在您的 getData 函数中:

do {
 self.arrdata = try JSONDecoder().decode([jsonstruct].self, from: data!)
 self.filteredArrData = self.arrdata
}

然后在您的表视图委托和数据源中:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{
   return self.filteredArrData.count
}

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

let cell:TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
   cell.label1.text = "Name: \(filteredArrData[indexPath.row].name)"
   cell.label2.text = "Capital: \(filteredArrData[indexPath.row].capital)"
   return cell
}

比像这样制作过滤器功能:

func applyFilters(textSearched: String) {
            filteredArrData = arrdata.filter({ item -> Bool in
            return item.name.lowercased().hasPrefix(textSearched.lowercased())
        })
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }

然后将你的字符串传递给这个函数,一切都会正常工作。


推荐阅读