我有一个自定义 UITableView 和一个带有 UISegmentedControl 的自定义 UITableViewCell。该单元格位于表格的第一行内。
问题是我正在使用 valueChanged 事件从 json 加载数据,当我重新加载 tableview 时,选择索引会自动返回到第一个段。我该如何解决这个问题?
这是我的代码的一部分:
@IBAction func segmentChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex{
case 0:
loadIdeas(idRole:[0,1], id_user: 1, estado: "todas")
case 1:
loadIdeas(idRole:[0,1], id_user: 1, estado: "aceptada")
case 2:
loadIdeas(idRole:[0,1], id_user: 1, estado: "pendiente")
case 3:
loadIdeas(idRole:[0,1], id_user: 1, estado: "rechazada")
default:
loadIdeas(idRole:[0,1], id_user: 1, estado: "todas")
}
}
我刷新“loadIdeas”函数中的数据,如下所示:
DispatchQueue.main.async{
self.table.tableView.reloadData() // Refrescamos el contenido de la tabla
}
每次我选择另一个段时,数据都会正确更改,但分段控件始终在重新加载数据之前保持选定的第一个段。
请帮帮我。我已经在这方面浪费了好几个小时了,而且我在网上没有找到任何可以帮助我的类似情况
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(cells[indexPath.row].cell == 1){
let cell = Bundle.main.loadNibNamed("CustomHeaderCell", owner: self, options: nil)?.first as! CustomHeaderCell
cell.menuLabel.text = cells[indexPath.row].titulo
return cell
}
else if(cells[indexPath.row].cell == 2){
let cell = Bundle.main.loadNibNamed("SegmentedControlCell", owner: self, options: nil)?.first as! SegmentedControlCell
cell.table = self
return cell
}
else{
let cell = Bundle.main.loadNibNamed("MyTableViewCell", owner: self, options: nil)?.first as! MyTableViewCell
cell.labelTitulo.text = cells[indexPath.row].titulo
cell.labelDescripcion.text = cells[indexPath.row].descripcion
cell.labelEstado.text = cells[indexPath.row].estado
cell.labelFecha.text = cells[indexPath.row].fecha
cell.labelDepartamento.text = cells[indexPath.row].departamento
//cell.imageView?.image = cells[indexPath.row].imagen
return cell
}
}
最佳答案
UITableView
数据源是一个不寻常的 API,需要习惯。 TableView 本身不知道(或记住)有关您的数据的任何信息,因此您必须在 tableView(_:cellForRowAt:)
方法中完全指定所有内容。换句话说,对于 SegmentedControlCell
情况,您需要有某种方法来保存当前选定的段并根据需要恢复它。
这可能意味着您的 cells
数组中与所选段相对应的任何类都具有某些属性。这有道理吗?
关于ios - Swift 3 : Segmented Control into TableView. 重新加载表时所选索引丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254801/