我有一个表格视图,其中每个单元格都是一个自定义表格视图单元格。该自定义tableview单元格包含一个tableview和一个标签。可以说,外部表视图称为MainTableView。 MainTableView的每个单元格都包含另一个tableview。问题是,当我选择内部tableview单元格一个接一个地取消选择先前选择的单元格。在第一个图像中,我选择的单元格包含文本“ Two”。然后,在第二张图像中,我选择的单元格包含文本“五”,但以前选择的单元格“第二”仍处于选择模式。选择新的单元格时,我想取消选择它。
我尝试过
tableView.deselectRow(at: IndexPath, animated: Bool)
此方法在自定义tableviewcell类的didSelectRowAt内部,但由于先前的indexPath来自单独的tableview而没有用。因此,如何取消选择上一个?
因为内部tableView彼此不相关。选择表一的单元格。不会影响表二中单元格的选择。
所以您应该手动建立连接。
使用属性存储状态var lastIndexPath: IndexPath?
,
然后每次选择一个indexPath,
if let last = lastIndexPath{
tableView.deselectRow(at: last, animated: true)
}
[请注意,您应该找到具有lastIndexPath
的正确内部tableView
先前的答案是正确的,但有一个缺陷-它无法区分tableViews,这是最重要的部分。另外,如果tableViews的行数不同,则可能会尝试访问不存在的行并导致崩溃。
要在两个tableViews(tv1
和tv2
)中跟踪选定的行,您需要在每个tableViews中保持选定的行:
var tv1, tv2: UITableView!
var lastRowForTV1, lastRowForTV2: IndexPath?
然后通过标识正在使用的tableView并调整其他tableView来响应选择(假定两个tableView使用相同的数据源/委托)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView === tv1 {
lastRowForTV1 = indexPath
if let last = lastRowForTV2 {
tv2.deselectRow(at: last, animated: true)
lastRowForTV2 = nil
}
} else if tableView === tv2 {
lastRowForTV2 = indexPath
if let last = lastRowForTV1 {
tv1.deselectRow(at: last, animated: true)
lastRowForTV1 = nil
}
}
}