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

如何将FirstVC的TableViewCell文本传递到SecondVC的TableView头部

解决FirstVC单元格文本传递到SecondVC表格头部标签的问题

问题根源

  1. FirstVC跳转SecondVC时,未将选中行的FirstTVCellModel数据传递给目标控制器
  2. SecondVC中直接打印insertionText对象(而非其userNameModel属性),导致显示内容不符合预期
  3. insertionText初始化时使用空字符串默认值,未接收来自FirstVC的真实数据

修复步骤

1. 调整SecondVC的接收变量

可选择直接接收用户名字符串(更轻量化),或保留模型类型(如需用到其他属性):

// SecondVC.swift
// 方案1:直接接收用户名字符串
var userName: String = ""

// 方案2:保留模型类型(若需使用dateModel等其他属性)
// var selectedPerson: FirstTVCellModel?

2. 在FirstVC跳转时传递数据

修改didSelectRowAt方法,将选中行的模型数据传给SecondVC:

// FirstVC.swift
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    firstTableView.deselectRow(at: indexPath, animated: true)
    if let vc = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondVC {
        // 获取选中的用户模型
        let selectedPerson = people[indexPath.row]
        // 对应方案1:传递用户名
        vc.userName = selectedPerson.userNameModel
        
        // 对应方案2:传递完整模型
        // vc.selectedPerson = selectedPerson
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

3. 在SecondVC中正确设置头部标签文本

修改viewDidLoad里的labelTwo文本赋值逻辑:

// SecondVC.swift
override func viewDidLoad() {
    super.viewDidLoad()
    // ... 其他原有代码不变 ...
    
    let labelTwo = UILabel(frame: tableHeader.bounds)
    // 对应方案1:使用传递的用户名
    labelTwo.text = "Inherited text here: \(userName)"
    
    // 对应方案2:使用模型中的用户名属性
    // labelTwo.text = "Inherited text here: \(selectedPerson?.userNameModel ?? "")"
    
    // ... 其他约束代码不变 ...
}

额外说明

表格头部高度自适应的问题,请单独在Stack Overflow提问处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 23:49:58