Join Todd Perkins for an in-depth discussion in this video Viewing the app's code structure visually, part of Programming for Non-Programmers: iOS 9 and Swift.
- Now before we get into writing the actual code, I want to talk about the structure of the code and some of the goals of our application so you have an idea of exactly what we're going to build before we build it. So here's the App Plan. We want to be able to tap numbers on the calculator and then see them at the top. Then the next step is to tap the plus or the minus button. Then we can tap buttons to add more numbers and then tap the equals button to see the result. Either the sum or the difference, depending on if the user tapped the plus or the minus button.
So in building this, we're also going to add a C button for clear. That's going to clear out the calculator and clear the screen and reset it to zero. Here are the instance variables that we're going to be using in this. Remember that your instance variables are also known as properties. We're going to have one called savedNum that is an integer. That's going to be used to hold the numeric values that are entered into the calculator. We're going to have one called currentMode that is of the type modes.
Now we haven't looked at the modes datatype because that's actually a custom datatype that we're going to write in this chapter. All that's going to control is whether the calculator is in addition mode, subtraction mode, or neither. Then we have lastButtonWasMode. This is a Boolean value, meaning true or false, which is going to give us true if the last button the user tapped was the plus or the minus button. Then we're going to have labelString. That's the string version of the calculator's total.
Then we'll have the label itself, the number at the top of the calculator. Now as far as methods go, we're going to have seven key methods that we're going to be writing code in. TappedClear is going to occur when the user taps the C button. TappedNumber is going to handle the number presses 0-9. TappedPlus for tapping the plus button, minus for the minus button, equals for the equals button. ChangeMode is going to call when the mode is being set either to addition or subtraction.
Finally, updateText is going to update the text within the label. Again, I just wanted to show you these so you have an idea of what we're going to build and how it's going to work before we start building it.
If you find you'd like to learn more, see iOS App Development Essential Training, Foundations of Programming: Fundamentals, or any of the other programming courses in our library.
- Installing Xcode
- Creating an Xcode project
- Configuring the iOS Simulator
- Understanding variables
- Connecting visual objects to variables
- Understanding functions, methods, and selectors
- Connecting a button to a method
- Using conditional statements
- Setting up the user interface
- Connecting code elements to build an app