如何过滤相同的数组名称多次在tableView与一个按钮?



我正在使用JSON,挑战是制作一个包含有关国家事实的应用程序。目前,我正在制作一个过滤器按钮来预览某个国家。但我只能使用一次,再次尝试时,会得到空tableView。我想做一个过滤器按钮每次都会迭代国家而不需要做重载按钮我需要点击重载所有国家然后再点击过滤器。MyCode:

import UIKit
class ViewController: UITableViewController {

var countries = [Countries]()
var countriesF = [Countries] ()

override func viewDidLoad() {
super.viewDidLoad()

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Filter", style: .plain, target: self, action: #selector(filtrate))
tableView?.alwaysBounceVertical = true
let urlString : String
urlString = "https://restcountries.eu/rest/v2/all"

if let url = URL(string: urlString){
if let data = try? Data(contentsOf: url){
parse(json: data)
countriesF = countries
return

}
}
}
func parse(json: Data){
let decoder = JSONDecoder()

if let country = try? decoder.decode([Countries].self, from: json){
countries = country
}
}
@objc func filtrate (){
let ac = UIAlertController(title: "Find", message: nil, preferredStyle: .alert)
ac.addTextField()
let filter = UIAlertAction(title: "Submit", style: .default){
[weak self, weak ac] _ in
guard let word = ac?.textFields?[0].text else {return}
self?.submit(for: word)

self?.tableView.reloadData()
}
ac.addAction(filter)
ac.addAction(UIAlertAction(title: "Cancle", style: .cancel))
present(ac, animated: true)

}
func submit(for filter: String){
countriesF = countriesF.filter{
$0.name.contains(filter)//ako je rec sadrzana u imenu...
}
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
countriesF.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath)
let country = countriesF[indexPath.row]
cell.textLabel?.text = country.name
return cell

}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(identifier: "Detail") as? DetailViewControler{

vc.detailItem = countriesF[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
}

countriesF = countriesF.filter{...

将自身过滤为death。你必须过滤整个数组

countriesF = countries.filter{...

永远不要用同步的Data(contentsOf从远程URL加载数据。它阻塞线程。使用异步方式。

最新更新