Eduardo Eduardo - 1 year ago 80
Swift Question

IOS Segue proper use

I have started learning ios. I come from a web development background.

I am getting a little confused when to use segue from the ViewController or from a specific button.

For example: if I have a

, then I have a button "Agree terms" when I tap it, It will take me to
. Should I create the segue from the "Agree terms" button or by selecting whole ViewController (from the topbar)? Which are the differences?

Thanks in advance

Answer Source

I tend to create a segue from the view controller itself.

You would then create an IBAction for the button on the view controller, and have the action call [self performSegueWithIdentifier:@"identifier"];

This is more or less exactly what creating the segue from a button does. If this is 100% all you need to do, that's perfectly acceptable. But this is a more maintainable solution, as it allows you to easily add additional functionality to buttons. I.e., say your button requires you to save an object to a server. You want to save that object before you move away from the page, so you'd put the performSegueWithIdentifier call in the completion block of the save.

Additionally, creating the segue from the storyboard with an identifier allows you to use that segue for multiple buttons. For example, say you have a view controller with 4 buttons that all go to an information page relating to that button. You only need one "goToInfo" segue on your storyboard, but you can set up 4 individual IBActions for those buttons that do different set up, then prepare the view controller based on the data set up in the IBActions for the buttons. This will keep your storyboard a bit cleaner, because instead of needing 4 different segues that are all visible on the SB, you only have the 1.

tl;dr - creating the segue from the button is fine as long as that is 100% the only thing you need to do when pushing the button. If there is anything else that needs to happen in the background, it would be better to create the segue from the VC, and call it via its identifier after you complete the additional steps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download