Search code examples
storyboardsingletonsegueviewcontrollerswift4.2

Performsegue from another viewcontroller doesnt' work


I've been using objective-C so far and decided to develop with swift since now.

I have no idea why this simple code doesn't work.

I have two viewControllers as container view from superview, one is called 'sideViewController' and the other one is 'dashViewController'.

I have a segue with identifier 'Appointment' from dashViewController to another viewController called 'nextViewController'

If i try to performsegue in dashViewController.swift, it works fine.

But why it doens't work if i try to use it in 'sideViewController'?

@IBAction public func buttonTapped(_ sender: Any) {
    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "dashboardViewController")
    vc.performSegue(withIdentifier: "Appointment", sender: self) //nothing happens
}

In objective C, I could use singleton for dashViewController like below

[[MainViewController sharedViewController] performSegueWithIdentifier:@"Appointment" sender:nil];

But in swift, following code doesn't work

DashboardViewController.sharedInstance.performSegue(withIdentifier: "Appointment", sender: nil)

I've been struggling with this for 2 days..

Please help me.

Thank you


Solution

  • In your buttonTapped() function, you are creating a new instance of "dashboardViewController", and then trying to perform a segue... but you haven't added that new VC or its view to the hierarchy, so even if the segue were to be performed, there's nothing to see.

    What you want to do is use the protocol / delegate pattern.

    Create a protocol so your button tap inside "sideViewController" can tell its delegate (the "main" view controller) to tell the existing instance of "dashboardViewController" to perform the segue.

    Protocols and delegates function the same in Swift as in Obj-C ... just different syntax.