Search code examples
iosswiftsegueviewcontrollerviewdidload

Same view controller loads twice


I've read several posts on this issue but none of them solved my problem.

I'm coding an app where I have to click on a button ("Prepare") to go to the following ViewController. When the button is clicked, it also passes data between the two view controller.

The problem is, when I click the button, the following ViewController loads twice. Thus, if I want to go back I have to go back through two same ViewController.

I've checked the segue, the class names and files names but nothing fixes it.
I've also created a new project and rewritten all the code from the beginning but in the end, it still doesn't work.

However, I've noticed that the problem showed up when I added the prepare(forSegue:) function and the performSegue function. Without it the ViewController only loads once. But of course, I can't get the data passed between the views without it...

Here is the screenshot of my two view and the code of the two functions :

First view
Second view

//    Prepare the segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "prepareSegue" {
        let timerViewController = segue.destination as! CountdownViewController
        timerViewController.timeInterval1 = waitingTime
        timerViewController.timeInterval2 = shootingTime
        timerViewController.lastSeconds = lastSeconds
        timerViewController.currentTimeInterval = waitingTime
    }
}

//    Prepare the timer when the button is pushed
@IBAction func prepareTimer(_ sender: Any) {
    performSegue(withIdentifier: "prepareSegue", sender: self)
}

Solution

  • Probably, when two ViewControllers appear it's because you have:

    1. A segue on Storyboard which start directly from a Button
    2. IBAction attached to the button where you call a performSegue of the same Segue

    To fix this problem, you need to create a Segue which start directly from ViewController. After you can use the IBAction and the performSegue