Skip to main content
April 1, 2026Noble Desktop Publishing Team/14 min read

Tip Calculator App: Free iOS Development Tutorial

Build Your First iOS Tip Calculator App

iOS Development Market Overview

22+
Apps on App Store
5
Programming Languages Supported
28
iOS Versions Released

Topics Covered in This iOS Development Tutorial:

Laying Out the UI with Modern Auto Layout Constraints

Core Development Skills You'll Learn

Interface Builder

Master Xcode's visual interface design tools and storyboard creation. Learn to drag, drop and configure UI elements.

Auto Layout System

Implement responsive design with constraints and stack views. Ensure your app looks great on all iPhone sizes.

Swift Programming

Write clean Swift code for user interactions and calculations. Connect interface elements to functional code.

Exercise Preview

tip calculator screenshot

Development Process Timeline

5 minutes

Project Setup

Create new Xcode project with proper configuration

15 minutes

UI Design

Layout interface elements and configure visual properties

10 minutes

Code Connection

Link interface to view controller with outlets and actions

15 minutes

Logic Implementation

Add calculation functionality and error handling

20 minutes

Responsive Design

Apply constraints for multiple device support

Exercise Overview

In this comprehensive exercise, you'll master the fundamentals of iOS development by building a polished tip calculator app from the ground up. This project demonstrates essential concepts including interface design, constraint-based layouts, outlet connections, and Swift programming fundamentals. By the end of this tutorial, you'll have a fully functional app that showcases professional iOS development practices and works seamlessly across all iPhone screen sizes.

Getting Started

We'll begin by setting up a new Xcode project with the proper configuration for modern iOS development. Follow these steps carefully to ensure your project foundation is solid:

  1. Launch Xcode (ensure you're using the latest version for optimal compatibility with current iOS versions).

  2. Navigate to File > New > Project to create a new iOS application.

  3. Under the iOS tab, select Application and double-click on App to choose the standard app template.

  4. Configure your project with the following essential settings:

    • Product Name: Tip Calculator
    • Team: None (maintain this setting for tutorial purposes)
    • Organization Name: Your Name
    • Organization Identifier: com.YourName (this creates a unique bundle identifier)
    • Interface: Storyboard (we'll use Interface Builder for visual design)
    • Language: Swift (Apple's modern, type-safe programming language)
    • Ensure both Use Core Data and Include Tests remain unchecked—these advanced features aren't needed for this project.
  5. Click Next to proceed to the save location dialog.

  6. Navigate to your designated project folder: Desktop > Class Files > yourname-iOS App Dev 1 Class.

  7. Verify that Create Git repository on My Mac is checked. This enables version control, allowing you to track changes and maintain project history—an essential practice in professional development.

  8. Click Create to finalize your project setup.

  9. Once Xcode displays the default project settings, locate Deployment Info > Device Orientation and uncheck both Landscape Left and Landscape Right. This constraint ensures your app maintains a portrait orientation, simplifying the design process for this tutorial.

Project Setup Requirements

0/6

Laying Out the UI

Now we'll construct the visual interface using Xcode's Interface Builder. This section demonstrates professional UI design principles and introduces you to the asset management system that's crucial for scalable app development.

  1. Our design requires three custom images for visual appeal. In the Project navigator project navigator icon, click on Assets to access the asset catalog—Apple's recommended system for managing app resources.

  2. Switch to Finder and navigate to yourname–iOS App Dev 1 Class > Tip Calculator Images folder.

  3. Select all three images within the folder using Command+A or click-and-drag selection.

  4. With Xcode visible, drag the three selected images directly into either column of the Editor. Xcode will automatically create appropriately named image sets in your asset catalog.

  5. Return to the Project navigator and select Main.storyboard to begin interface design.

  6. At the bottom of the Editor, ensure the view is set to iPhone 13 Pro for optimal design reference during development.

  7. Using the preview screenshot as your design guide, we'll systematically add each interface element. In the Object library object library icon search field, type image and drag an Image View onto the view controller.

  8. Select the newly added image view and open the Attributes inspector attributes inspector icon. In the Image field, type bg-gradient and press Return to assign the background gradient.

  9. Resize the image view to completely fill the screen—this will serve as our app's background foundation.

  10. Add a second Image View from the Object library for the header graphic.

  11. In the Attributes inspector, set this new image view's Image property to top-graphic.

  12. By default, Xcode scales images to fit their containers, which can distort proportions. To maintain visual integrity, locate the Content Mode setting under the View section and change it to Aspect Fit. This preserves the image's original aspect ratio.

  13. The top graphic contains transparency that requires special handling. To ensure consistent display across devices, we'll add a constraint. Control-drag from the image view to itself in the Document Outline and select Aspect Ratio.

  14. Open the Size inspector and edit the aspect ratio constraint, setting the Multiplier to 720:268—the exact pixel dimensions of our image. Don't worry about missing constraint warnings at this stage; we'll address positioning later.

    Professional Tip: To determine any image's exact dimensions, drag it into Google Chrome and hover over the browser tab to see the pixel dimensions displayed.

  15. Resize the tip calculator graphic to approximate the size shown in our reference layout.

  16. Next, we'll add the interactive button. In the Object library object library icon, search for Button and drag one to the center of your view.

  17. In the Attributes inspector, clear the default Button text from the Title field—we'll use a custom image instead.

  18. Set the button's Image property to button-calculate-tip for a professional, custom appearance.

  19. Now we'll add text labels for our interface. Search for Label in the Object library object library icon and drag three labels onto the view. These will display Bill, Tip, and % respectively.

  20. Select each label individually and update their text in the Attributes inspector attributes inspector icon to read Bill, Tip, and %.

  21. For consistent styling, select all three labels using Shift+Click and set their Color to White for optimal contrast against the dark background.

  22. While all three labels remain selected, click the font formatting button font format next to Font and configure:

    • Font: System
    • Style: Light (provides a modern, clean appearance)
    • Size: 24 (ensures good readability)
  23. Set text Alignment to Left and resize the label frames as needed to accommodate the text properly.

  24. Position these labels to match the reference screenshot layout, maintaining consistent spacing and alignment.

  25. Add user input fields by searching for Text Field in the Object library and dragging two text fields onto the view—one for bill amount input and another for tip percentage.

  26. Select both text fields simultaneously to apply consistent formatting.

  27. In the Attributes inspector, set the font to System Light with a Size of 20 for excellent readability.

  28. Configure text Alignment to Right to create a clean, organized appearance.

  29. Ensure the Border Style is set to the rounded edges option (the rightmost border style) for a polished, modern look.

  30. Select the top text field (for bill amount) individually.

  31. Open the Size inspector size inspector icon and set the Width to 101 pixels for optimal bill amount display.

  32. Select the bottom text field (for tip percentage) and set its Width to 70 pixels—smaller since percentage values are typically shorter.

  33. With the tip percentage field still selected, return to the Attributes inspector and add default text: 15. This provides users with a reasonable starting value and demonstrates the field's purpose immediately.

  34. Select both text fields again for coordinated color styling.

  35. Click the Color property to open the system Colors panel.

  36. Along the panel's top navigation, click the second button to access Color Sliders.

  37. From the dropdown menu, choose RGB Sliders for precise color control.

  38. In the Hex Color # field, enter 003945 and press Return. This dark teal provides excellent contrast and professional appearance.

  39. Close the color panel and position both text fields according to your reference screenshot.

  40. Add two additional labels from the Object library for displaying calculated results—tip amount and total bill with tip included.

  41. Although our code will update these dynamically, we'll add placeholder text for visual alignment purposes. Select the top result label and enter: Tip Amount: $10.85 in the Attributes inspector.

  42. Resize this label as needed to accommodate the full text string.

  43. Select the bottom result label and set its text to: Total: $65.08, resizing as necessary.

  44. Select both result labels and apply consistent formatting:

    Font: System
    Style: Light
    Size: 22
    Alignment: Right
    Color: White
  45. Perform a final alignment pass, ensuring all interface elements match the professional layout shown in the reference screenshot.

Essential UI Components Setup

1

Background Image

Add gradient background image and scale to fill entire screen for visual appeal

2

Header Graphic

Insert top graphic with aspect ratio constraint to maintain proportions

3

Input Fields

Create text fields for bill amount and tip percentage with proper styling

4

Calculate Button

Add custom button with image for triggering calculations

5

Output Labels

Place labels for displaying calculated tip amount and total bill

Image Constraint Best Practice

Use exact pixel dimensions for aspect ratio constraints to prevent image warping. Drag images into Chrome to view their precise dimensions.

Connecting the Interface to the ViewController

This crucial phase transforms your visual interface into a functional app by establishing connections between interface elements and Swift code. These connections, known as outlets and actions, form the foundation of user interaction in iOS development.

  1. Access the Assistant Editor by clicking Adjust Editor Options then Show the Assistant editor assistant editor icon. This displays your storyboard and corresponding Swift code side by side.

  2. We'll begin by creating outlets—connections that allow your code to reference interface elements. Hold the Control key and drag from the bill amount text field to the ViewController.swift code, positioning just below this line:

    class ViewController: UIViewController {
  3. In the connection dialog that appears, name the outlet billPrice and press Return to confirm.

  4. Xcode generates this line of code: @IBOutlet weak var billPrice: UITextField!

    Understanding the Code: The @IBOutlet attribute (where IB stands for Interface Builder) tells Xcode this variable connects to an interface element. The weak keyword prevents memory retention cycles, while UITextField! specifies the exact interface element type.

  5. Control-drag from the tip percentage text field (the bottom field) and name this outlet tipPercent in the resulting dialog.

  6. Create an outlet for the tip amount result label by Control-dragging from that label and naming it tipLabel.

  7. Similarly, create an outlet for the total bill result label and name it totalLabel.

    Your outlet connections should now look like this in code:

    @IBOutlet weak var billPrice: UITextField!
    @IBOutlet weak var tipPercent: UITextField!
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var totalLabel: UILabel!
  8. Actions differ from outlets—they respond to user interactions rather than simply referencing interface elements. Control-drag from the Calculate Tip button to your ViewController.swift file and configure the action with these specific settings:

    Connection: Action (this setting is crucial!)
    Name: calculate
    Type: UIButton
    Event: Touch Up Inside

    Professional Insight: Actions are methods that execute when users interact with interface elements. All executable code belongs between the opening and closing curly braces {}. When users tap the button, iOS calls this method and executes each contained instruction sequentially.

  9. Click Connect to establish the action relationship.

IBOutlet vs IBAction Connections

FeatureIBOutletIBAction
PurposeReference UI elementsHandle user interactions
Connection TypePropertyMethod
UsageRead/modify element propertiesExecute code on user action
ExamplebillPrice: UITextFieldcalculate(_ sender: Any)
Recommended: Use outlets for elements you need to modify, actions for user interactions

Adding the Calculator Logic

Now we'll implement the mathematical logic that transforms user input into calculated results. This section demonstrates fundamental Swift programming concepts including type conversion, mathematical operations, and string formatting.

  1. We must convert text field contents (strings) into numerical values (doubles) for mathematical calculations. Add this line of code between the curly braces of your calculate method:

    @IBAction func calculate(_ sender: Any) {
       let price = Double(billPrice.text!)
    }

    Code Explanation: This statement creates a constant called price by converting the bill text field's string content into a Double (decimal number) that enables mathematical operations.

  2. Apply the same conversion process to the tip percentage field by adding this code:

    let price = Double(billPrice.text!)
    let tip = Double(tipPercent.text!)

    Note: Yellow warning indicators can be ignored at this stage—they'll resolve as we complete the implementation.

  3. Calculate the actual tip amount using straightforward mathematical operations with our newly created constants:

    let tip = Double(tipPercent.text!)
    let tipTotal = price! * tip!/100.0

    Mathematical Breakdown: This multiplies the bill amount by the tip percentage, then divides by 100 to convert the percentage into a decimal multiplication factor.

  4. Display the calculated tip amount in the interface by updating the tip label's text property:

    let tipTotal = price! * tip!/100.0
    tipLabel.text = String(format: "$%.2f", tipTotal)

    Formatting Details: The format string "$%.2f" ensures currency display with exactly two decimal places, maintaining professional financial formatting standards.

  5. Enhance user experience by adding descriptive text that clearly identifies the calculated value:

    tipLabel.text = "Tip Amount: " + String(format: "$%.2f", tipTotal)

    String Concatenation: The + operator joins text strings, combining our descriptive label with the formatted currency amount.

  6. Complete the calculator functionality by computing and displaying the total bill (original amount plus tip):

    tipLabel.text = "Tip Amount: " + String(format: "$%.2f", tipTotal)
    totalLabel.text = "Total: " + String(format: "$%.2f", price! + tipTotal)
  7. Set the active simulator scheme to iPhone 8 in the top-left scheme selector for initial testing.

  8. Click the Run button run icon to compile your code and launch the app in the iOS Simulator.

    Troubleshooting Alert: You may notice the top graphic appears distorted! This occurs because we haven't fully constrained its layout behavior yet.

  9. Return to Xcode and Control-drag from the top-graphic image view to itself, selecting Width from the constraint options.

  10. Open the Size inspector and modify this width constraint, setting the Constant to ≤ 323. This creates a maximum width limit of 323 pixels, preventing oversizing on larger devices. Position issues will be resolved shortly with additional constraints.

  11. Run the simulator again to verify the graphic scaling improvement.

  12. Test your calculator functionality by entering a value in the Bill field and tapping Calculate Tip. The app should correctly compute a 15% tip based on your input!

  13. Experiment with different bill amounts and tip percentages to verify the calculator handles various scenarios accurately.

  14. You may observe that result labels appear immediately when the app launches, before any calculations occur. Professional apps typically hide output until meaningful data exists. Let's implement this improvement.

    Return to Xcode's code editor.

  15. Locate the viewDidLoad function and replace the default comment with code that initializes both result labels as empty strings:

    override func viewDidLoad() {
       super.viewDidLoad()
       tipLabel.text = ""
       totalLabel.text = ""
    }

    Method Purpose: The viewDidLoad function executes once when the view controller loads, making it ideal for initial setup tasks like hiding result labels until calculations occur.

  16. Run the app again and notice the improved user experience—only input fields and the calculate button appear initially, creating a cleaner interface.

  17. Test edge case handling by leaving the Bill field completely empty and pressing Calculate Tip.

    Critical Issue: The app crashes and returns to Xcode! This demonstrates why error handling is essential in professional development. String-to-Double conversion can fail, requiring defensive programming techniques.

  18. Implement robust error handling using Swift's guard statement—a conditional structure that ensures safe execution. Add this protective code:

    @IBAction func calculate(_ sender: Any) {
    
       guard let price = Double(billPrice.text!)
       else { return }
    
       let tip = Double(tipPercent.text!)

    Guard Statement Logic: This checks if the bill text can be converted to a valid Double. If conversion fails (empty field, invalid text), the else block executes return, immediately stopping function execution and preventing crashes.

  19. Remove the now-unnecessary force unwrapping operators (!) from the price variable references, as shown below—the guard statement already handles the optional unwrapping safely:

    let tipTotal = price * tip!/100.0
    
    tipLabel.text = "Tip Amount: " + String(format: "$%.2f", tipTotal)
    totalLabel.text = "Total: " + String(format: "$%.2f", price + tipTotal)
  20. Click Stop then Run to test the improved error handling.

  21. Test the fix by leaving the Bill field empty and pressing Calculate Tip. Your app should now handle this gracefully without crashing—a hallmark of professional app development! Take a moment to appreciate your fully functional, crash-resistant tip calculator.

Calculation Logic Implementation

1

Data Conversion

Convert text input to Double values for mathematical operations

2

Tip Calculation

Multiply bill amount by tip percentage divided by 100

3

Display Formatting

Format currency values with two decimal places using String formatting

4

Error Handling

Implement guard statements to prevent crashes from invalid input

Crash Prevention

Always validate user input before conversion. Empty text fields will crash the app when cast to Double without proper error handling.

Adding Constraints

While your app functions perfectly on iPhone 8, it likely appears broken on other device sizes. This section addresses responsive design through Auto Layout constraints—Apple's system for creating interfaces that adapt beautifully to any screen size. Mastering constraints is essential for professional iOS development in 2026, where apps must work seamlessly across the entire iPhone lineup.

Let's transform your single-device design into a universally compatible interface that maintains its visual integrity across all iPhone models from the iPhone SE to the iPhone 15 Pro Max.

  1. Return to Xcode and select Main.storyboard in the Project navigator to begin constraint implementation.

  2. Close the Assistant Editor by clicking the X in its top-left corner—we need maximum screen space for constraint work.

  3. Start with the background by selecting bg-gradient in the Document Outline. This foundational element should fill the entire screen on any device.

  4. Click the Add New Constraints button pin button at the bottom right of the Editor to access the constraint configuration panel.

  5. Ensure all four constraint values (top, bottom, leading, trailing) are set to 0 for edge-to-edge positioning.

  6. Activate all four constraints by clicking the red dotted lines until they become solid red—this indicates active constraints.

  7. For each constraint, click the dropdown arrow constraint arrow and select View (current distance = 0) to pin the background to the main view's edges.

  8. Click the Add 4 Constraints button to implement the background constraints. Your background should now fill any device screen completely.

Auto Layout Constraint Types

Edge Constraints

Pin elements to screen edges with specific distances. Essential for background elements and safe area alignment.

Size Constraints

Control width and height of UI elements. Prevents unwanted stretching and maintains proportions.

Alignment Constraints

Center elements or align them relative to other views. Creates consistent spacing and positioning.

Key Takeaways

1Xcode's Interface Builder provides visual tools for designing iOS app interfaces without writing layout code
2Proper project configuration including orientation settings and asset management is crucial for professional app development
3IBOutlets connect interface elements to code properties while IBActions handle user interaction events
4Swift's guard statements and optional binding prevent crashes by safely handling invalid user input
5Auto Layout constraints ensure apps display correctly across different iPhone screen sizes and orientations
6Stack views simplify responsive design by automatically managing element positioning and spacing
7String formatting with currency symbols and decimal places creates professional user experiences
8Working from inside-out when creating nested UI hierarchies leads to more maintainable interface code

RELATED ARTICLES