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

Xcode 13.1中prepare(for segue:)触发后目标ViewController被调用两次的问题求助

Hey there, let's dig into why your DestinationViewController is being called twice—this is a super common gotcha with Storyboard segues! Here are the most likely causes and fixes to check:

1. Duplicate Segue Triggers (The #1 Culprit)

This happens way more often than you'd think: your startButton is probably triggering the segue twice—once via a Storyboard connection, and once via your startButtonTapped IBAction.

How to check:

Open your Storyboard, select the startButton, then open the Connections Inspector (press ⌥⌘6). Look at the sections for Segues and Received Actions:

  • If you see both a segue named goToNextViewControllerSegue linked to the button, and the startButtonTapped action linked, that's the problem.

Fix:

Pick one way to trigger the segue and stick with it:

  • Option A: Delete the Storyboard segue connection (right-click the segue line and select Delete), keep your startButtonTapped logic with performSegue.
  • Option B: Remove the performSegue call from your IBAction, and add a guard using shouldPerformSegue to enforce your tag condition:
    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if identifier == "goToNextViewControllerSegue" {
            return tag == 1 || tag == 2
        }
        return true
    }
    
2. Multiple IBAction Connections

Another possibility: your button is connected to startButtonTapped more than once. This means clicking the button runs the action twice, which calls performSegue twice.

How to check:

Again, use the Connections Inspector for your button. Look at the Received Actions section—if startButtonTapped appears more than once, that's the issue.

Fix:

Delete the duplicate connections (click the little "x" next to the extra entries).

3. Accidental performSegue Calls Elsewhere

Double-check if any other part of your code is calling performSegue(withIdentifier: "goToNextViewControllerSegue"). For example, maybe it's accidentally added in viewDidLoad, viewWillAppear, or another button's action.

How to check:

Do a global search in your project for the segue identifier "goToNextViewControllerSegue"—look for any unexpected performSegue calls.

Quick Guard Rail Tip

To prevent this from happening in the future, relying on shouldPerformSegue (like the example in Option B above) is a great practice. It centralizes your segue logic and acts as a safety net against accidental duplicate triggers.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:14:08