Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform Segue From Another Swift File via a class function [closed]

Tags:

ios

swift

How can I use a class function I implement to perform a segue if the class it is held in is not connected to a viewController?

like image 889
Tyler Patrick Avatar asked Dec 05 '25 13:12

Tyler Patrick


2 Answers

In order to perform a segue, you need the instance of view controller where the segue originates from - for example:

class MyViewController {
}

class MyClass {
    showNextView(fromViewController: UIViewController) {
        fromViewController.performSegueWithIdentifier("segue_id", sender: fromViewController)
    }
}

However I discourage this kind of interaction. Don't tell the view controller how to show a view - let it do on its own, and just ask it.

So, I suggest creating an instance method in your view controller:

class MyViewController {
    ...
    func goToNextView() {
       performSegueWithIdentifier("segue_id", sender: self)
    }
}

and use that to make the transition:

class MyClass {
    showNextView(fromViewController: MyViewController) {
        fromViewController.goToNextView()
    }
}
like image 92
Antonio Avatar answered Dec 11 '25 20:12

Antonio


You can instruct the currently visible view controller to segue using "performSegueWithIdentifier".

You obviously need a reference to the visible controller.

Inside your method use:

currentViewController.performSegueWithIdentifier("push", sender: currentViewController)
like image 45
joakim Avatar answered Dec 11 '25 20:12

joakim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!