Swift实现UITableView点击Cell跳转ViewController并传递文本至TextField
解决UITableViewCell点击后传值到新ViewController的问题
这个场景用属性传值是最直接且易维护的方案,我结合你的需求分两种常见实现方式来讲解:
第一步:给新ViewController添加接收属性
首先,假设你的新ViewController叫TextInputViewController,先在这个类里定义一个用来接收选中文本的属性,然后在viewDidLoad里把值赋值给TextField:
class TextInputViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! // 定义接收选中文本的属性 var selectedCellText: String? override func viewDidLoad() { super.viewDidLoad() // 将传过来的文本填充到TextField inputTextField.text = selectedCellText } }
第二步:根据你的跳转方式实现传值
场景1:用代码初始化并跳转(纯代码/XIB场景)
在你的NearbyViewController里补全tableView(_:didSelectRowAt:)方法,获取选中的文本后,直接给新VC的属性赋值再跳转:
class NearbyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var nearbyTableView: UITableView! var myList: [String] = [] // 补全数据源方法 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) cell.textLabel?.text = myList[indexPath.row] return cell } // 处理Cell点击事件并传值 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 获取被点击Cell的文本 let selectedText = myList[indexPath.row] // 初始化新的ViewController let textInputVC = TextInputViewController() // 给新VC的属性赋值 textInputVC.selectedCellText = selectedText // 跳转(根据页面结构选push或present) navigationController?.pushViewController(textInputVC, animated: true) // 如果没有导航栏,用present: // present(textInputVC, animated: true, completion: nil) } }
场景2:用Storyboard Segue跳转(可视化布局场景)
如果你的页面跳转是通过Storyboard拖Segue实现的:
- 先在Storyboard里给
NearbyViewController和TextInputViewController之间拖一个Segue,设置Segue的Identifier为GoToTextInputVC(自定义名字)。 - 在
NearbyViewController里实现以下代码:
class NearbyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var nearbyTableView: UITableView! var myList: [String] = [] // 补全数据源方法 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) cell.textLabel?.text = myList[indexPath.row] return cell } // 点击Cell时触发Segue func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "GoToTextInputVC", sender: myList[indexPath.row]) } // 准备Segue时传值 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "GoToTextInputVC" { // 安全转换目标VC类型 guard let textInputVC = segue.destination as? TextInputViewController else { return } // 将选中的文本赋值给目标VC的属性 textInputVC.selectedCellText = sender as? String } } }
这样就能完美实现你要的效果:点击Cell后打开新页面,且TextField自动填充选中Cell的文本。
内容的提问来源于stack exchange,提问作者user8788401
相关产品推荐
相关产品推荐

