1
votes

I have 2 view controllers (VC1 & VC2). Both of them are made programmatically without InterfaceBuilder. I'm trying to segue from VC1 to VC2 through code. I know there are methods like:

  • performSegue(withIdentifier: String, sender: Any?)
  • prepare(for: UIStoryboardSegue, sender: Any?)

But I don't have VC2 identifier and I don't have Storyboard. So how to segue through code? Just 5 days with Swift. Thank you in advance.

2

2 Answers

5
votes

Segues are specific to Storyboards (hence the class name – UIStoryboardSegue). If you want to perform a transition from VC1 to VC2 programmatically you have two options:

  1. Present VC2 modally in VC1:

    let vc2 = VC2()
    self.present(vc2, animated: true)
    
    // to return from VC2 to VC1 call this somewhere in VC2
    self.dismiss(animated: true)
    
  2. Wrap VC1 in a UINavigationController and then push VC2 to it when needed:

    let vc2 = VC2()
    self.navigationController?.pushViewController(vc2, animated: true)
    
    // to return from VC2 to VC1 call this somewhere in VC2
    self.navigationController?.popViewController(animated: true)
    
-2
votes

Segues are a storyboard thing. You can't use segues without storyboards.

The simple answer to your question is that you can't do that. If you don't use storyboards, you can't use UIStoryboardSegues. That's why they're called storyboard segues. Segues are provided by Storyboards.

Stop fighting the tools and start using Storyboards. (I would not hire somebody who said "I don't use Storyboards. I write all my interfaces in code" any more than I would hire somebody who eschews high level languages and does everything in assembly language. Yes it's possible, but why would you do that?)