Search code examples
iosswiftuiviewcontrollerswift4uistoryboardsegue

overriding "prepare for segue" when programmatically creating a UIViewController


I have a UIView, inside it I'm creating a UIViewController:

class TopBarView: UIView {
    var viewController: UIViewController?{
        didSet{
           print("a")
    }
}

later in my code, I'm performing a segue using:

if let vc = viewController {
    vc.performSegue(withIdentifier: "imagesSegue", sender: nil)
}

I wish to pass some parameters to the UIViewController I'm performing the segue to.

I tried to add a "prepare for segue" definition inside the definition of the viewcontroller, so it would look like this:

class TopBarView: UIView {
    var viewController: UIViewController?{
        didSet{
           print("a")
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    }
}

However, I'm getting an error - such a thing probably cannot be done.

How can I pass the required parameters into the new UIViewController?


Solution

  • This

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       /////
    }
    

    Should be inside the vc that you assign to var viewController: UIViewController? and use sender parameter to send any data

    vc.performSegue(withIdentifier: "imagesSegue", sender:"someStr")
    

    Note: You can't use a segue if the vc is created programmatically