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

求助:如何实现满足条件时在Segue间传递值并执行Segue

解决ViewController间带条件的Segue传值问题

Hey there! Let's work through this together—this is a super common scenario, and the fix boils down to taking control of when your segue actually fires instead of letting it trigger automatically. Here's how to make it work:

步骤1:把自动触发的Segue改成手动触发

If you currently have a button (or any UI element) directly linked to the segue in your storyboard, disconnect that first. Instead, add an IBAction to the button so we can run our condition check before deciding whether to launch the segue.

@IBAction func goToNextVCTapped(_ sender: UIButton) {
    // 先判断expensesRecieved的数量是否符合要求
    if expensesRecieved.count > 0 {
        // 满足条件,手动触发Segue
        performSegue(withIdentifier: "YourCustomSegueID", sender: self)
    } else {
        // 不满足条件,弹出提示框
        let alert = UIAlertController(title: "提示", message: "没有可传递的费用数据哦", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

步骤2:在prepareSegue中安全传递数据

Now that we only trigger the segue when our condition is met, we can safely pass the data in the prepare(for:sender:) method. First, make sure your destination ViewController has a property to receive the data.

目标ViewController的接收属性:

class DestinationViewController: UIViewController {
    // 用来接收传递过来的费用数据(替换成你的实际数据类型)
    var passedExpenses: [YourExpenseModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 这里就可以使用passedExpenses做后续处理了
        print("收到的费用数据:\(passedExpenses)")
    }
}

原ViewController的prepareSegue实现:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // 确认是我们要处理的Segue
    if segue.identifier == "YourCustomSegueID" {
        // 强转目标ViewController,确保类型正确
        guard let destVC = segue.destination as? DestinationViewController else { return }
        // 传递数据
        destVC.passedExpenses = expensesRecieved
    }
}

为什么你之前的尝试可能失败?

If you were using a storyboard-connected segue (dragging directly from a button to the next VC), the prepare(for:sender:) method runs before any of your custom condition checks. That means the segue would fire even if expensesRecieved was empty, which is exactly what you're trying to avoid. By triggering the segue manually in code, we get full control over when it executes.

Don't forget to set the correct segue identifier in your storyboard: select the segue, go to the Attributes Inspector, and fill in the same ID you used in the code (like "YourCustomSegueID").

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:29:09