Agung
Agung

Reputation: 13813

3 ways of view controller transition

i am a beginner in iOS development, and recently, i just follow along the tutorial for beginners.

let say i want to move from one VC to another VC by clicking a button, so i just find out that there are three ways to move from one ViewController to another ViewController (modal segue).

  1. in main storyboard, i just click control and drag from the button to th destination view controller and choose present modally

  2. programmaticaly, by implementing the code below

    @IBAction func logInButtonDidPressed(_ sender: Any) {
    
    
    
    // modal transition to VC2
    
    let viewController2 = 
    storyboard?.instantiateViewController(withIdentifier: 
    "ViewController2") as! ViewController2
    
    present(viewController2, animated: true, completion: nil)
    
    
    
    }
    
  3. programatically,by using perform segue function

    @IBAction func logInButtonDidPressed(_ sender: Any) {
    
    
    performSegue(withIdentifier: "toSecondViewController", sender: self)
    
    
    
    }
    

are they just the same ? or is it used for different cases?

Thanks in advance :)

Upvotes: 0

Views: 62

Answers (2)

Yun CHEN
Yun CHEN

Reputation: 6648

Yes, they are similar. And the obvious difference I think is the data passing. The first and third one are same, use the following method to pass data to next controller:

// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if let viewController2 = segue.destination as? ViewController2 {
        viewController2.someProperty = someValue
    }
}

For second transition, you directly set the data when creating the next controller:

let viewController2 = storyboard?.instantiateViewController(withIdentifier: 
"ViewController2") as! ViewController2

viewController2.someProperty = someValue

present(viewController2, animated: true, completion: nil)

Upvotes: 2

Palle
Palle

Reputation: 12109

I would use segues, as there are some advantages compared to manual presentation:

  • You can create unwind segues to exit the current view controller to any view controller in the hierarchy.

  • You can add 3D touch support to segues with one mouse click.

The first and last method produce identical results. I would create segues with clicking and dragging whenever possible. If you need to do some data validation or other stuff before performing a transition, you have to call the performSegue method manually.

Upvotes: 2

Related Questions