Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
like image 536
BedWolf Avatar asked Sep 18 '25 09:09

BedWolf


2 Answers

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

like image 171
Giuseppe Sapienza Avatar answered Sep 21 '25 00:09

Giuseppe Sapienza


You have added a seague but also an IBAction. If the seague is defined well in InterfaceBuilder it will perform and call your method. The IBAction is the alternative way for connecting an Action to a button. If you use both, you have two actions.

like image 26
Christian Avatar answered Sep 20 '25 23:09

Christian