【问题标题】:Tableview cell did select row action based on selectionTableview 单元格确实根据选择选择了行操作
【发布时间】:2025-12-22 23:05:11
【问题描述】:

我有一些问题和答案

问题归一列,答案归一列。

我想在用户选择问题时再次显示答案选择关闭答案。

我写了下面的代码,但是当一个答案是开放的时候仍然是所有的都是关闭的,我的逻辑是相反的任何一个请帮助我。

这里我创建了一个带有 selectedindex 名称的全局变量

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DonationTableViewCell", for: indexPath)as!
    DonationTableViewCell
    cell.questioncell.text = questnArr[indexPath.row]

    if indexPath.row  == selectedindex
    {
        cell.answerlbl.text = answersarr[indexPath.row]
        cell.questioncell.textColor = UIColor.disSatifyclr
        cell.questionimg.image = #imageLiteral(resourceName: "Drop down top icon")

    }else{
        cell.answerlbl.text = ""
        cell.questioncell.textColor = UIColor.textmaincolor
        cell.questionimg.image = #imageLiteral(resourceName: "Drop down")

    }
    tableviewheight.constant = tableview.contentSize.height

    return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedindex = indexPath.row
    tableView.reloadData()
}

【问题讨论】:

  • 不清楚你在问什么。您的问题与行高有关吗?如果是这样,请出示您的heightForRowAt
  • cellForRowAt 中的tableviewheight.constant = tableview.contentSize.height 行有什么意义?那不应该在那里。

标签: ios swift uitableview uibutton


【解决方案1】:

首先将selectedindex 声明为可选IndexPath

var selectedIndexPath : IndexPath?

didSelectRowAt 你必须进行一些检查:

  • 如果selectedIndexPath == nil 选择indexPath 处的行
  • 如果selectedIndexPath != nilselectedIndexPath == indexPath 取消选择indexPath 处的行
  • 如果selectedIndexPath != nilselectedIndexPath != indexPath 取消选择selectedIndexPath 处的行并选择indexPath 处的行。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedIndexPath == nil {
        selectedIndexPath = indexPath
        tableView.reloadRows(at: [indexPath], with: .automatic)
    } else {
        if indexPath == selectedIndexPath! {
           selectedIndexPath = nil
           tableView.reloadRows(at: [indexPath], with: .automatic)
        } else {
           let currentIndexPath = selectedIndexPath!
           selectedIndexPath = indexPath
           tableView.reloadRows(at: [currentIndexPath, indexPath], with: .automatic)
        }
    }
}

cellForRowAt检查

if indexPath == selectedIndexPath

【讨论】: