fs_tigre fs_tigre - 3 months ago 11
Swift Question

Go to second viewController without segues

In the following code I have an action/button that when tapped takes you to a different viewController (

SecondViewController
), everything works fine but there is a line of code that I don't fully understand.

What is this line of code doing?


secondVC.delegate = self


What delegate are we talking about here? Is that really needed if I only need to go to other view and I'm not passing any data?

@IBAction func goToView(sender: AnyObject) {
let secondVC= storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as! SecondViewController
secondVC.delegate = self // is this needed?
self.presentViewController(secondVC, animated:true, completion:nil)
}

Answer
  1. secondVC.delegate = self

This line of coding is passing object reference of current class in which you are standing to SecondViewController. Now, you can call methods of firstViewController(I assume this name), by using delegate object in secondViewController.

  1. This delegate is not needed

, if you simply want to go to Next Screen which is SecondViewController in your case.

  1. Helpful code:

Following will pass you to next controller, make sure that you have navigationController or not. As in NavigationController, you have to pushViewController into stack.

@IBAction func goToView(sender: AnyObject) {  
    let secondVC= storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as! SecondViewController  
    self.presentViewController(secondVC, animated:true, completion:nil)
} 

or in case of NavigationController

@IBAction func goToView(sender: AnyObject) {  

let secondVC = self.storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as? SecondViewController
    self.navigationController?.pushViewController(secondVC!, animated: true)
}

I hope my descriptive answer will help you. Feel free to ask any query in comments.

Thanks.

Comments