iOS Tutorials: Passing data using callback method

Swift 4.2 | Xcode 10

OVERVIEW

There are many different ways to pass information from one screen to another. One easy way I’ve found is using callback. The scenario here is that the user will be presented a screen with a button. Now when the user press the button, he will then enter into another screen to pick his food. Once he picks his food, he will then go back to the initial screen with the same information and the cost of the food before he could make a payment.

DESIGNING THE STORYBOARD

The first screen will contains the following:

  1. Embed with Navigation Controller
  2. Label for title
  3. Bolded label
  4. ImageView
  5. Button

The second screen contains:

  1. Label for title
  2. Four Image View

WRITING THE CALLBACK METHOD

We are hoping here again that when a user click on burger on the second screen, it will return burger and potentially additional information to the first screen. Before we proceed, make sure you have two view controller attached to both view on the storyboard.

Some of the things need to be implemented in the first screen first before we move into the next screen.

First Controller: Create a segue from first controller to second controller 

With this, we are able to connect the information from first screen to the second screen. You will see shortly that burger is actually a closure in the second view controller.

First Controller: Create a function to inherit the information

With the code above, we are connecting the closure from a second view controller with our function in the first view controller. And if the user click on the burger, it will pass the necessary information. The variable inside are just some variable I’ve created in the controller.

Second Controller: Create a closure and IBOutlet

You’ve seen in the previous step that we needed to have a closure called burger that takes in string. With that, I’ve created a closure that takes in both string. Now remember, that this is connected with the func prepare(for segue: UIStoryboardSegue created previously.

Second Controller: Add action 

I’ve created a GestureRecognizer for the image, hoping that when a user tap on the image, it will trigger the function and pop the controller to return to the first screen.

Remember the closure that we created that takes in two string? Now this is where we assign the data.

Once you are done with this, you could create three more foods. If you are still having difficulty figuring out, dont worry. I’ve uploaded the code onto GitHub

SEE THE ACTION

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*