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

Swift 4:点击TableViewCell按钮后通过Segue向另一ViewController传数据

我来帮你搞定这个问题!核心症结是你需要先把Cell按钮点击拿到的postId传递回ViewController1,再通过Segue把它传给ViewController2,具体实现步骤如下:

步骤1:给TableViewCell添加回调机制(用闭包更简洁)

在你的TableViewCell类里定义一个闭包属性,用来在按钮点击时把postId传递给ViewController1:

class YourTableViewCell: UITableViewCell {
    // 假设你的按钮已通过IB关联
    @IBOutlet weak var actionButton: UIButton!
    // 用来存储当前cell对应的postId
    var postId: String? // 根据你的实际类型调整,比如Int
    // 按钮点击的回调闭包
    var onButtonTap: ((String) -> Void)?

    @IBAction func buttonTapped(_ sender: UIButton) {
        guard let currentPostId = postId else { return }
        // 触发回调,把postId传出去
        onButtonTap?(currentPostId)
    }
}
步骤2:在ViewController1中接收postId并触发Segue

在ViewController1的tableView(_:cellForRowAt:)方法里,给Cell的闭包赋值,保存选中的postId并执行Segue:

class ViewController1: UIViewController, UITableViewDataSource {
    // 临时存储选中的postId,用于后续Segue传递
    var selectedPostId: String?
    // 假设你的数据源是posts数组
    var posts: [PostModel] = []

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier", for: indexPath) as! YourTableViewCell
        let currentPost = posts[indexPath.row]
        // 给Cell设置对应的postId
        cell.postId = currentPost.postId
        // 配置Cell的其他UI元素...
        
        // 设置回调闭包,接收postId并触发Segue
        cell.onButtonTap = { [weak self] postId in
            self?.selectedPostId = postId
            // 执行Segue,替换成你在Storyboard中设置的Segue标识符
            self?.performSegue(withIdentifier: "ToViewController2", sender: nil)
        }
        return cell
    }
}
步骤3:在Segue准备方法中传递postId到ViewController2

重写ViewController1的prepare(for:sender:)方法,把保存的selectedPostId传给ViewController2:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ToViewController2" {
        // 强转目标控制器为ViewController2
        guard let vc2 = segue.destination as? ViewController2 else { return }
        // 把postId赋值给ViewController2的接收属性
        vc2.receivedPostId = selectedPostId
    }
}
最后检查点
  • 确保ViewController2中已经定义了接收postId的属性,比如var receivedPostId: String?
  • 确认Storyboard中Segue的标识符和代码里的一致
  • 闭包中使用[weak self]是为了避免循环引用,防止内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:36:46