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

Swift4中如何获取TableView多选行数据并在另一个VC的TableView展示

嘿,我太懂你折腾两天卡壳的烦躁了!咱们把问题拆成几步来解决,其实核心就是把选中的索引映射到数据源,再把数据传递到目标VC就行,没那么复杂~

第一步:把选中的索引转换成对应的数据

首先假设你的数据源是按 section 组织的二维数组(比如 var dataSource: [[YourCellDataType]] = [],YourCellDataType 是你自定义的结构体/类,用来存每个cell的两个标签文本、图片这些数据)。

你现在拿到的 [[0,1], [0,2], [0,3]] 这种格式,每个子数组就是 [section, row] 的组合。那咱们遍历这个数组,从数据源里把对应的数据捞出来:

// 假设你的选中索引数组叫 selectedIndexPairs
let selectedIndexPairs = [[0, 1], [0, 2], [0, 3]]
var selectedData: [YourCellDataType] = []

for indexPair in selectedIndexPairs {
    let section = indexPair[0]
    let row = indexPair[1]
    // 加个判断防止越界崩溃,毕竟万一索引和数据源不匹配就麻烦了
    guard section < dataSource.count, row < dataSource[section].count else {
        continue
    }
    let item = dataSource[section][row]
    selectedData.append(item)
}

哦对了,要是你是直接从TableView的indexPathsForSelectedRows拿到选中项的话,其实用IndexPath数组更靠谱,不用自己转二维数组:

if let selectedIndexPaths = tableView.indexPathsForSelectedRows {
    selectedData = selectedIndexPaths.compactMap { indexPath in
        guard indexPath.section < dataSource.count, indexPath.row < dataSource[indexPath.section].count else {
            return nil
        }
        return dataSource[indexPath.section][indexPath.row]
    }
}
第二步:把选中的数据传到目标VC

接下来就是把selectedData传递到另一个视图控制器,最直接的方式是给目标VC加个属性:

先在目标VC里声明:

class TargetViewController: UIViewController {
    // 类型要和你的数据类型完全匹配
    var selectedItems: [YourCellDataType] = []
    // 其他代码比如TableView的初始化之类的...
}

然后在你触发跳转的地方(比如点击确认按钮),初始化目标VC并把数据传过去:

// 假设用Storyboard跳转,记得替换成你自己的VC标识符
if let targetVC = storyboard?.instantiateViewController(withIdentifier: "TargetVC") as? TargetViewController {
    targetVC.selectedItems = selectedData
    // 跳转方式根据你的导航结构来,push或者present都可以
    navigationController?.pushViewController(targetVC, animated: true)
}
第三步:在目标VC的TableView里展示数据

最后就是在目标VC的TableView数据源方法里用selectedItems来渲染cell:

extension TargetViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 选中多少条就显示多少行
        return selectedItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 替换成你自己的cell标识符和自定义cell类型
        let cell = tableView.dequeueReusableCell(withIdentifier: "TargetCell", for: indexPath) as! YourCustomTargetCell
        let item = selectedItems[indexPath.row]
        // 给cell的控件赋值
        cell.firstLabel.text = item.firstLabelText
        cell.secondLabel.text = item.secondLabelText
        cell.cellImageView.image = item.cellImage
        return cell
    }
}

这样一套流程走下来,选中的数据就能顺利传递并展示啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:45:55