【发布时间】:2020-06-22 07:17:11
【问题描述】:
我想根据用户在搜索栏中输入的内容在表格视图上显示所有城市名称。 例如,如果用户在 searchBar 中键入“New York”,我希望显示 API 给我的所有结果。 我正在使用返回 JSON 数据的 API。
现在我正在使用这个委托方法:
extension searchViewController : UISearchBarDelegate{
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
RequestAPI.queryCities(cityNameString: searchBar.text!) { (cities) in
for iterator in 0...cities.geonames.count-1 {
self.citiesQueried.append(cities.geonames[iterator])
}
}
self.tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
print("cancel button clicked")
self.citiesQueried.removeAll()
self.tableView.reloadData()
}
}
citiesQueried 是我之前在 viewController 中声明为空的数组,它的任务是收集 API 请求产生的所有数据。
这些是 UITableView 的委托方法:
extension searchViewController : UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return citiesQueried.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCityTableViewCell", for: indexPath)
cell.textLabel?.text = self.citiesQueried[indexPath.row].name
return cell
}
}
问题是它有时有效,有时无效,我需要按两次搜索按钮才能看到 tableView 上显示的城市。 我认为缺少一些东西,我希望你们中的一些人能给我一些关于如何解决这个问题的建议
【问题讨论】:
-
从 API 成功重新加载您的 tableView。
-
您需要在
queryCities的完成处理程序闭包中调用reloadData,并记住将其分派到主队列中
标签: ios swift api uitableview uisearchbar