重新加载部分后无法取消选择 tableView 行

Cannot deselect tableView row after reloading section

我正在实现一个分段的 tableView,它会在您单击 header 部分时展开部分行。它在大多数情况下都有效,但是当您 select 一行,折叠该部分,然后展开该部分时,您无法取消 select 之前 select 编辑的行。我不确定我哪里出错了。另一件事是调试器正在打印出我以前从未见过的 [Assert] Unable to determine new global row index for preReloadFirstVisibleRow (0) 或知道它是否与问题有关。我在 didDeselectdidSelect 函数中放置了断点,一切都按预期命中,直到出现我上面解释的情况

@objc func headerPressed(sender: UIButton) {
    if (!tableDataSource[sender.tag][0].clicked) {
        tableDataSource[sender.tag][0].clicked = true
    } else {
        tableDataSource[sender.tag][0].clicked = false
    }
    let sections = IndexSet.init(integer: sender.tag)
    tableView.reloadSections(sections, with: .fade)
}

func numberOfSections(in tableView: UITableView) -> Int {
    return tableDataSource.count
}
    
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableDataSource[section][0].clicked ? tableDataSource[section].count : 0
}
    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "ModifierCell") as? ModifierCell else { return UITableViewCell() }
        
    let mod = tableDataSource[indexPath.section][indexPath.row]
    cell.modNameLabel.text = mod.mod.id!
    cell.setSelected(mod.selected, animated: true)
    cell.checkImage.image = mod.selected ? UIImage(systemName: "checkmark.circle") : UIImage(systemName: "circle")
    
    return cell
}
    
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.setSelected(tableDataSource[indexPath.section][indexPath.row].selected, animated: false)
}
    
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! ModifierCell
    cell.checkImage.image = UIImage(systemName: "checkmark.circle")
    tableDataSource[indexPath.section][indexPath.row].selected = true 
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! ModifierCell
    cell.checkImage.image = UIImage(systemName: "circle")
    tableDataSource[indexPath.section][indexPath.row].selected = false
}

// .....

struct tableElement {
    var mod: Modifier
    var clicked = false
    var selected = false
}

我从您的实际设置中遗漏了一些信息,但是应该解决这个问题...

将您的 willDisplay cell 函数替换为:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if tableDataSource[indexPath.section][indexPath.row].selected {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }
    //cell.setSelected(tableDataSource[indexPath.section][indexPath.row].selected, animated: false)
}