如何从嵌套TableView Cell向UIViewController传递数据并获取点击索引
解决嵌套Cell按钮点击并获取外层Cell索引的方案
步骤1:完善自定义Cell C的Delegate协议
修改你的Delegate协议,让方法携带当前Cell C的实例,方便ViewController通过实例获取索引:
protocol CustomCellCDelegate: AnyObject { func c1ButtonClicked(in cell: CustomCellC) func c2ButtonClicked(in cell: CustomCellC) }
同时在CustomCellC中用weak修饰delegate属性,避免循环引用:
weak var delegate: CustomCellCDelegate?
步骤2:更新c1/c2按钮的IBAction方法
在按钮点击时,把当前Cell C实例传给Delegate方法:
@IBAction func buttonInC1Cell(_ sender: Any) { delegate?.c1ButtonClicked(in: self) } @IBAction func buttonInC2Cell(_ sender: Any) { delegate?.c2ButtonClicked(in: self) }
步骤3:在ViewController中实现Delegate方法并获取索引
让ViewController遵循CustomCellCDelegate协议,通过TableView的indexPath(for:)方法,从传入的Cell C实例中拿到对应的索引:
extension ViewController: CustomCellCDelegate { func c1ButtonClicked(in cell: CustomCellC) { guard let indexPath = tableView.indexPath(for: cell) else { return } // 这里可以用indexPath做后续操作,比如获取对应数据源 print("c1按钮触发,外层Cell索引:\(indexPath.row)") } func c2ButtonClicked(in cell: CustomCellC) { guard let indexPath = tableView.indexPath(for: cell) else { return } print("c2按钮触发,外层Cell索引:\(indexPath.row)") } }
步骤4:给Cell C设置Delegate
在TableView的cellForRowAt方法中,将ViewController设置为Cell C的delegate:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellC", for: indexPath) as! CustomCellC cell.delegate = self // 完成Cell C的其他数据配置 return cell }
备选方案:直接给Cell C绑定indexPath
如果觉得通过TableView获取索引不够直接,也可以给Cell C添加indexPath属性,在cellForRowAt时赋值:
// 在CustomCellC中添加属性 var indexPath: IndexPath? // 在cellForRowAt中赋值 cell.indexPath = indexPath
然后修改Delegate方法直接传递indexPath:
protocol CustomCellCDelegate: AnyObject { func c1ButtonClicked(at indexPath: IndexPath?) func c2ButtonClicked(at indexPath: IndexPath?) } // 按钮点击方法 @IBAction func buttonInC1Cell(_ sender: Any) { delegate?.c1ButtonClicked(at: indexPath) }
这种方式更直接,但要注意Cell复用场景下indexPath的准确性,第一种方案的实时获取方式更稳妥。
内容的提问来源于stack exchange,提问作者mefahimrahman
相关产品推荐
相关产品推荐

