Swift中通过另一UITableView选中行更新当前UITableView行标签的实现方法
实现方案
你可以通过闭包反向传值的方式实现需求,修改代码如下:
1. 修改 CountryViewController.swift
首先给国家选择控制器新增回调闭包,选中国家时触发回调传值:
import UIKit class CountryViewController: UIViewController { // 新增:回调闭包,参数为用户选中的国家名称 var countrySelected: ((_ country: String) -> Void)? // 你的原有其他属性,比如CountryList数组 // 你原有cellForRowAt代码保持不变 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CountryCell", for: indexPath) as! CountryTableCell cell.lblTitle.text = CountryList[indexPath.row] return cell } // 修改didSelectRowAt方法,选中后触发回调 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCountry = CountryList[indexPath.row] // 触发回调回传选中的国家 countrySelected?(selectedCountry) self.navigationController?.popViewController(animated: true) } }
2. 修改 FirstViewController.swift
跳转时接收回调,更新数据源后局部刷新对应行即可:
import UIKit class FirstViewController: UIViewController { // 你的原有属性,比如customData数组、tableView出口 // 修改cellForRowAt方法,从数据源读取存储的国家名称 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableCell let dict = customData[indexPath.row] as? [String: Any] // 如果你用的是自定义模型对应修改类型即可 cell.lblTitle.text = "Title" // 放开原有注释,从数据源读取选中的国家展示 cell.lblSubTitle.text = dict?["selectedCountry"] as? String ?? "请选择国家" cell.selectedButton.tag = indexPath.row cell.selectedButton.addTarget(self, action: #selector(buttonClick), for: .touchUpInside) return cell } // 修改buttonClick方法,实现回调逻辑 @objc func buttonClick(sender: UIButton){ let countryVC = CountryViewController(nibName: nil, bundle: nil) // 拿到当前点击的行索引 let targetRow = sender.tag // 实现国家选中的回调逻辑 countryVC.countrySelected = { [weak self] selectedCountry in guard let self = self else { return } // 第一步:更新数据源对应位置的国家字段 if var dataDict = self.customData[targetRow] as? [String: Any] { dataDict["selectedCountry"] = selectedCountry self.customData[targetRow] = dataDict as NSObject // 如果你用的是自定义模型,修改为对应赋值逻辑即可: // var model = self.customData[targetRow] as? YourCustomModel // model?.selectedCountry = selectedCountry // self.customData[targetRow] = model } // 第二步:局部刷新对应行,性能更高 self.tableView.reloadRows(at: [IndexPath(row: targetRow, section: 0)], with: .none) } self.navigationController?.pushViewController(countryVC, animated: true) } }
注意事项
- 必须先更新数据源,再执行刷新操作,否则UITableView读取的还是旧数据,界面不会更新
- 闭包中添加
[weak self]避免循环引用导致内存泄漏 - 优先用
reloadRows(at:with:)局部刷新对应行,不要直接调用tableView.reloadData()全量刷新,性能更优
内容的提问来源于stack exchange,提问作者Rakshit Kumar
相关产品推荐
相关产品推荐

