【发布时间】:2019-01-28 21:26:46
【问题描述】:
我使用 Swift 制作了一个 TableView,其中显示了 UiTextField 中填充的查询的搜索结果。
let cellReuseIdentifier = "cell"
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SearchCell = self.tableView.dequeueReusableCell(withIdentifier:cellReuseIdentifier) as! SearchCell
cell.objectName.text = self.search_results_list[indexPath.section]
return cell
}
在 Value Changed 事件中,我触发了 Search 操作:
@IBAction func searchInputChanged(_ sender: Any) {
self.search_results_list = []
let search = self.searchField.text
let parameters: Parameters = ["api_token": token, "search": search!+" "]
let URL = "https://myweb.app/api/search"
Alamofire.request(URL, parameters: parameters).responseArray { (response: DataResponse<[SearchResponse]>) in
let searchResultsArray = response.result.value
if let searchResultsArray = searchResultsArray {
for searchResult in searchResultsArray {
self.search_results_list.append(searchResult.description!)
}
}
// Then I reloeadData of the TableView
self.tableView.reloadData()
}
}
还有 NumberOfSections 方法:
func numberOfSections(in tableView: UITableView) -> Int {
return self.search_results_list.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
确实有效,但是当我快速填写表格时,Array 的顺序正确,但 TableView 的顺序不同。当我检查数组时,我发现顺序是正确的,但 TableView 显示的是不同的。当我等待一秒钟并在最后添加一个空格时,TableView 确实显示了正确的顺序。 当我逐个字母添加并在每个字母后等待重新加载 tableview 时也是如此,输出是正确的
我错过了什么?
【问题讨论】:
-
一个潜在的问题是,如果您快速点击“ab”,您将搜索“a”,然后搜索“b”。但是由于调用是异步的,您的服务器可能会快速响应“ab”,然后响应“a”,因此您的结果是错误的,因为它仅适用于“a”,而您当前的文本是“ab”。
-
@Larme 我检查了服务器并且输入正确发送,它显示了正确的值。但实际上,看起来已经给出了一个新的输出,但还没有被 Swift 渲染或其他东西
-
@AshleyMills 根本没用
-
这需要一个堆栈,将请求添加到 ,如果不是来自最顶部的项,则忽略响应
-
@Sh_Khan 我不明白你的意思,你能简单解释一下吗?谢谢
标签: ios swift uitableview alamofire