我已经使用 Alamofire 和 SwiftyJSON 解析了一个 JSON,以获取加密货币名称列表并填充表格 View 。然后我尝试使用 UISearchBar 过滤结果,但无论我搜索什么,它总是显示名称数组的第一个结果,即使过滤器在我使用 print 测试它并且正确过滤时正在工作。例如,我搜索 Ethereum 并且控制台打印 ["name": "Ethereum"] 但 Tableview 将始终显示“Bitcoin”,如果我搜索一个不存在的名称,它什么也不显示。任何人都可以确定我的代码中导致此问题的错误吗?非常感谢,我对任何类型的编码都不熟悉。
这是我的代码:
//
// StartViewController.swift
// CryptoClockTesting
//
// Created by Peter Ruppert on 08/07/2018.
// Copyright © 2018 Peter Ruppert. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class StartViewController: UIViewController, UISearchBarDelegate,
UITableViewDelegate, UITableViewDataSource {
var names = [[String:String]]()
var isSearching = false
var filteredData = [[String:String]]()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let name = names[indexPath.row]
let text: [String:String]
if isSearching {
text = filteredData[indexPath.row]
print(text)
} else {
text = name
}
cell.textLabel?.text = name["name"]
cell.textLabel?.textColor = UIColor.blue
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
} else {
isSearching = true
filteredData = names.filter({
$0["name"] == searchBar.text
})
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching {
return filteredData.count
} else {
return names.count
}
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
tableView.isHidden = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
tableView.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.isHidden = true
searchBar.delegate = self
tableView.delegate = self
tableView.dataSource = self
searchBar.returnKeyType = UIReturnKeyType.done
self.view.backgroundColor = .blue
let urlString = "https://api.coingecko.com/api/v3/coins"
if let url = URL(string: urlString) {
if let data = try? String(contentsOf: url) {
let json = JSON(parseJSON: data)
parse(json: json)
}
}
}
//Parsing News API and adding to table, then use table view setup to properly display.
func parse(json: JSON) {
for result in json[].arrayValue {
let name = result["name"].stringValue
let obj = ["name": name]
names.append(obj)
}
tableView.reloadData()
}
}
最佳答案
这是因为您总是将它设置为 cellForRowAt
中的 name["name"]
if isSearching {
text = filteredData[indexPath.row]
print(text)
} else {
text = name
}
cell.textLabel?.text = name["name"] // should be text["name"]
关于swift - 我的 UISearchBar 结果有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303245/