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:
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
goToNextViewControllerSeguelinked to the button, and thestartButtonTappedaction 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
startButtonTappedlogic withperformSegue. - Option B: Remove the
performSeguecall from your IBAction, and add a guard usingshouldPerformSegueto enforce your tag condition:override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == "goToNextViewControllerSegue" { return tag == 1 || tag == 2 } return true }
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).
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.
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

