Present uiviewcontroller from ParentViewController in Swift 4

347 views Asked by At

I have a parentview which has 2 child views, I am trying to show a uiviewcontroller as "Present modally" I use the following code:

class ParentCtrl: ButtonBarPagerTabStripViewController {
    let obj = ChildCtrl()
override func viewDidLoad() {
        super.viewDidLoad()
        obj.someClassMethod()
    }
}

class ChildCtrl: UIViewController, IndicatorInfoProvider {
   struct Storyboard {
    static let segue_id = "segue_id"
}
   public func someClassMethod(){
        self.performSegue(withIdentifier: Storyboard.segue_id, sender: self)
    }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == Storyboard.segue_id){
            let destino = segue.destination as! NewViewController
            destino.seleccion = seleccion
        }
    }
}

But I get the following error:

has no segue with identifier 'segue_id'' But Yeah, I have that identifier because if I copy:

self.performSegue(withIdentifier: Storyboard.segue_id, sender: self)

in the viewDidload method the NewViewController is presented

How can I solve that?

2

There are 2 answers

7
PGDev On

Specify the Storyboard Segue identifier, i.e.

enter image description here

And use this id while writing the code to perform segue, i.e.

self.performSegue(withIdentifier: "segue_id", sender: self)

Edit:

Create obj from storyboard, i.e.

let obj = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ChildCtrl") as! ChildCtrl
6
Paulw11 On

You are simply creating an instance of ChildCtrl rather than using the instance that came from the storyboard. As a result, that instance doesn't know anything about any storyboard file and therefore has no context to perform a segue.

You need to perform the segue from the instance of ChildCtrl that is on screen.