Search code examples
iosswiftuiviewcontrolleruitextfieldsegue

Using the same text field data for a calculation in different view controllers depending on options selected


I'm new to Swift and Xcode trying to find my way. I'm learning what I can through struggle, practice, and asking questions. Please excuse my novice level knowledge.

I'm developing an app in which the user will go through a series of questions, each on its own screen containing buttons with different options and sometimes a text field for them to enter a value.

My goal is to be able to use the text field data as variables for one calculation in a final view controller that displays a label with results for the user.

For example, on one view controller, there are two buttons to choose from... one is tapped if they want to know what they need on the final exam ("buttonFinalTakenYes") and another if they want to know what they need on the final before they take it ("buttonFinalTakenNo")...

then no matter what the choice, the next screen asks for their current grade in the class and they will enter a number into a text field and press next...

After a few more questions, depending on what they want to know, I want the final view controller to perform a calculation using all the numbers entered from the text fields leading up to it and display a result as a label. Basically, there are different equations that will display a result based on what the user wants to calculate, and each result will be on a different view controller using data from previous text fields.

I tried searching for answers but I can't seem to figure out what kind of code I need to use for this.

I know that I need to convert the String from the text fields into doubles so they can be used for calculations... but anything beyond that, I'm stuck.

I tried playing around with delegates and segues but it didn't work. Do I need if statements somewhere? Do I need to establish a new protocol? Also, would NSUserDefaults be relevant to this or is it just passing data between view controllers? What if the final view controller is many after the original text field?

Any guidance is appreciated. I feel like I'm making this harder than it needs to be.

Thank you so much!


Solution

  • 👋 Glad to see that you are staying positive and asking questions instead of giving up.

    I suggest you look up MVC (Model View Controller) because what you are missing in your code currently is the Model part. You need an object that holds all of the data the user entered throughout the app. Each view controller should add it's bit of data to this Model and then pass the model on to the next view controller in the chain.

    By the time you are at the last view controller, you will have a Model object that contains all the data the user entered and you can do your calculations on that data and display the result in your last view controller's label.