当 segmentedControl
索引在滚动 tableView
时更改时,我在 cellForRowAt
中得到“Index out of range
” >.
@IBAction func segmentedControlAction(_ sender: AnyObject!) {
if(segmentedControl.selectedSegmentIndex == 0) {
self.data?.removeAll()
loadA()
}
else if(segmentedControl.selectedSegmentIndex == 1){
self.data?.removeAll()
loadB()
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomCell
cell.data = self.data?[indexPath.row] ---> Error here
return cell
}
LoadA 和 LoadB 是相似的函数
func loadA(){
API.sharedInstance.loadA(start, callback: { response in
if let data = response["data"].arrayValue as [JSON]?{
self.data = data
DispatchQueue.main.async {
self.tableView?.reloadData()
}
}
})
}
最佳答案
您首先删除所有数据但不重新加载表。然后调用一个异步方法,该方法稍后会在后台更新数据,最后开始在主队列中重新加载 TableView 。
您只需在重新加载 TableView 之前立即更新数据模型。
@IBAction func segmentedControlAction(_ sender: AnyObject!) {
if(segmentedControl.selectedSegmentIndex == 0) {
loadA()
}
else if(segmentedControl.selectedSegmentIndex == 1){
loadB()
}
}
func loadA(){
API.sharedInstance.loadA(start, callback: { response in
if let data = response["data"].arrayValue as [JSON]?{
DispatchQueue.main.async {
self.data = data
self.tableView?.reloadData()
}
}
})
}
关于swift - UITableView - 滚动时选择段时索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090758/