You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现UITableView单元格跳转至不同ViewController?代码失效求助

问题根源

你的代码只通过indexPath.row判断跳转逻辑,没有区分UITableView的分区(section)。如果两个分区中存在行号相同的单元格(比如两个分区的第0行),它们会触发同一个segue,导致跳转到同一个页面。

解决方案

1. 修改单元格点击事件,同时判断分区和行号

更新tableView(_:didSelectRowAt:)方法,加入分区判断,确保不同分区的对应单元格触发正确的segue:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 根据分区+行号的组合判断跳转目标
    if indexPath.section == 0 && indexPath.row == 0 {
        performSegue(withIdentifier: "toSettings1", sender: nil)
    } else if indexPath.section == 1 && indexPath.row == 0 {
        performSegue(withIdentifier: "toSettings2", sender: nil)
    }
    // 如果每个分区有多个单元格,继续补充对应的section+row判断条件
}

2. 验证Storyboard配置

确认Storyboard中:

  • 标识符为toSettings1的segue,目标控制器是ReferencesViewController
  • 标识符为toSettings2的segue,目标控制器是LiabilityViewController
    避免出现segue指向错误控制器的情况。

可选优化:用映射关系简化判断

如果后续需要扩展更多跳转规则,可以用数组映射管理分区、行号和segue的对应关系,减少冗余的if-else:

// 提前定义分区+行号与segue标识符的对应关系
private let segueConfig: [(section: Int, row: Int, segueID: String)] = [
    (0, 0, "toSettings1"),
    (1, 0, "toSettings2")
]

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 查找匹配的配置项
    if let config = segueConfig.first(where: { $0.section == indexPath.section && $0.row == indexPath.row }) {
        performSegue(withIdentifier: config.segueID, sender: nil)
    }
}

内容的提问来源于stack exchange,提问作者Dilan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:58:12