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

如何通过AlertBox和CoreData在UITableViewCell间跨场景传递数据?

实现AlertBox选中数据传递到另一Scene的UITableViewCell

我来帮你一步步实现这个需求~首先我们得先处理AlertBox的点击事件拿到选中数据,再选择合适的方式把数据传递到目标Scene,最后在目标Scene的TableView里展示出来。

第一步:完善AlertBox的点击逻辑,获取选中数据

假设你的SupplementScene里有一个数据源数组(比如var supplements: [Supplement] = []),先在TableView的点击方法里弹出Alert,并在确认按钮的回调中拿到选中的Supplement数据:

// 先确保你的Supplement模型已经定义,比如:
struct Supplement {
    let name: String
    let detail: String
    // 其他属性根据你的需求添加
}

class SupplementScene: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var lblSupplement: UILabel!
    @IBOutlet weak var sbSupplement: UISearchBar!
    @IBOutlet weak var tvSupplement: UITableView!
    let stackScene = StackScene()
    var supplements: [Supplement] = [] // 你的数据源数组

    // TableView点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        // 拿到当前选中的Supplement
        let selectedItem = supplements[indexPath.row]
        
        // 创建AlertBox
        let alert = UIAlertController(title: "选择补充剂", message: "确定要选择「\(selectedItem.name)」吗?", preferredStyle: .alert)
        
        // 确认按钮:在这里处理数据传递
        alert.addAction(UIAlertAction(title: "确认", style: .default, handler: { [weak self] _ in
            self?.sendSelectedDataToStackScene(data: selectedItem)
        }))
        
        // 取消按钮
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        present(alert, animated: true)
    }

    // 后续实现这个数据传递方法
    private func sendSelectedDataToStackScene(data: Supplement) {
        // 下面分不同场景实现
    }
}

第二步:选择合适的方式传递数据到目标Scene

根据你的页面跳转方式,这里给你两种最常用的实现方案:

方案1:通过Storyboard Segue跳转传递数据

如果你的SupplementScene是通过Storyboard里的Segue跳转到StackScene,按以下步骤做:

  1. 在Storyboard里给Segue设置一个唯一的Identifier(比如"ToStackScene")
  2. 实现sendSelectedDataToStackScene方法和Segue的准备方法:
private func sendSelectedDataToStackScene(data: Supplement) {
    // 通过Segue跳转,把选中的数据作为sender传递
    performSegue(withIdentifier: "ToStackScene", sender: data)
}

// 重写Segue准备方法,给目标VC传递数据
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ToStackScene", 
       let targetVC = segue.destination as? StackScene,
       let selectedData = sender as? Supplement {
        // 给StackScene设置接收数据的属性
        targetVC.selectedSupplement = selectedData
    }
}

然后在StackScene里定义接收属性,并在TableView的数据源方法中使用:

class StackScene: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tvStack: UITableView!
    // 定义接收数据的属性
    var selectedSupplement: Supplement?

    override func viewDidLoad() {
        super.viewDidLoad()
        tvStack.reloadData() // 数据传递过来后刷新TableView
    }

    // TableView数据源方法:展示传递过来的数据
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1 // 假设只展示一条选中的数据,根据你的需求调整
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StackCell", for: indexPath)
        if let supplement = selectedSupplement {
            cell.textLabel?.text = supplement.name
            cell.detailTextLabel?.text = supplement.detail
        }
        return cell
    }
}

方案2:通过代码初始化目标VC传递数据

如果是通过代码手动push/present到StackScene,可以这样实现:

private func sendSelectedDataToStackScene(data: Supplement) {
    // 从Storyboard初始化StackScene(如果是纯代码VC就直接初始化)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let stackVC = storyboard.instantiateViewController(withIdentifier: "StackScene") as? StackScene else {
        print("无法初始化StackScene")
        return
    }
    
    // 传递数据
    stackVC.selectedSupplement = data
    
    // 跳转方式二选一:push到导航栈
    navigationController?.pushViewController(stackVC, animated: true)
    // 或者present模态跳转
    // present(stackVC, animated: true)
}

方案3:跨已存在的Scene传递(比如TabBar页面)

如果StackScene是已经存在的页面(比如TabBar的某个标签页),可以用通知中心来传递数据:

  1. 在SupplementScene的Alert确认回调里发送通知:
alert.addAction(UIAlertAction(title: "确认", style: .default, handler: { _ in
    NotificationCenter.default.post(
        name: NSNotification.Name("SupplementSelectedNotification"),
        object: nil,
        userInfo: ["selectedSupplement": selectedItem]
    )
}))
  1. 在StackScene里注册通知并处理:
class StackScene: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tvStack: UITableView!
    var selectedSupplement: Supplement?

    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleSupplementSelected(_:)),
            name: NSNotification.Name("SupplementSelectedNotification"),
            object: nil
        )
    }

    // 处理通知,更新数据和TableView
    @objc private func handleSupplementSelected(_ notification: Notification) {
        if let supplement = notification.userInfo?["selectedSupplement"] as? Supplement {
            selectedSupplement = supplement
            tvStack.reloadData()
        }
    }

    // 记得销毁时移除观察者,避免内存泄漏
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    // 数据源方法和前面一样,省略...
}

注意事项

  • 确保你的Supplement模型是可以正常传递的,如果是结构体直接传值就行,如果是类要注意引用关系
  • 闭包里记得用weak self避免内存泄漏
  • Storyboard里的VC Identifier、Segue Identifier一定要和代码里的一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:49:06