ios - 如何在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()
}
解决方案
您需要制作两个数据对象,一个是原始数据,另一个是过滤后的数据。
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()
}
}
然后将你的字符串传递给这个函数,一切都会正常工作。
推荐阅读
- axios - Axios 错误响应数据被格式化为可以在浏览器中看到。我想要原始堆栈
- javascript - 如何使用 JavaScript 调用 AWS Textract 服务上传本地照片进行识别(无 S3)
- python - 如何使用 keras 和 tensorflow 的 ImageDataGenerator 执行数据增强
- python - Python 中的刽子手游戏
- database - (Oracle) 数据泵兼容性?
- python - 将 Python Kivy 代码转换为 .exe 文件时出现问题
- java - 如何从 java 代理停止/停止主程序/线程
- php - PHP:将内存 sqLite 数据库转储到文件
- android - React Native Build 随机失败
- python - tkinter 和 python 中的多线程