Skip to content

Making the App Interactive

iOS Development with Swift - Making Your App Interactive

Section titled “iOS Development with Swift - Making Your App Interactive”

Static apps are informative, but interactive apps engage users. In this chapter, we’ll explore how to make your iOS app respond to user input. We’ll cover:

  • Adding Text Fields (UITextField) for user input
  • Using Labels (UILabel) to display dynamic information
  • Adding Buttons (UIButton) and handling their actions (tap events)

We’ll build a simple app, for example, a ‘Dog Age Calculator’, where the user enters their dog’s age in human years, and the app calculates and displays the equivalent age in dog years (using a simple multiplier).

To begin, create a new Xcode project (iOS App template, Storyboard interface, Swift language) or use an existing one. Let’s name it ‘InteractiveAppDemo’.

Designing the User Interface in Storyboard

Section titled “Designing the User Interface in Storyboard”

Open your Main.storyboard file.

  • Add a Label for the title: Drag a UILabel from the Object Library onto your view. Double-click it and set its text to ‘Dog’s Age Calculator’. Position it near the top.
  • Add a Text Field for input: Drag a UITextField from the Object Library. Place it below the title label. In the Attributes Inspector (right-hand pane, select the text field first), you can set a ‘Placeholder’ text like ‘Enter dog’s age in human years’. For numeric input, change the ‘Keyboard Type’ to ‘Number Pad’.
  • Add a Button to trigger calculation: Drag a UIButton below the text field. Double-click it or use the Attributes Inspector to change its title to ‘Calculate Age’.
  • Add a Label for the result: Drag another UILabel below the button. This label will display the calculated age. Initially, you can clear its text or set it to something like ‘Result will appear here’. Stretch it a bit horizontally to accommodate longer results.

Tip: If you can’t edit an element’s text by double-clicking, select the item and find its ‘Text’ (for labels) or ‘Title’ (for buttons) property in the Attributes Inspector. Press Return/Enter after changing.

Optionally, add an image to make the UI more visually appealing:

  1. Find a suitable image (e.g., a dog icon). Add it to your project’s Asset Catalog (Assets.xcassets). Drag the image file from Finder into the asset catalog. Give it a descriptive name (e.g., ‘dog_icon’).
  2. In Main.storyboard, drag an UIImageView from the Object Library onto your view.
  3. With the Image View selected, go to the Attributes Inspector. In the ‘Image’ dropdown, select the name of the image you added (e.g., ‘dog_icon’).
  4. Adjust the Image View’s size and position. Set its ‘Content Mode’ (e.g., ‘Aspect Fit’ or ‘Aspect Fill’) to control how the image scales.

Arrange these UI elements neatly on your view. Consider using Auto Layout constraints or Stack Views for a responsive design, though for this simple example, fixed positions might suffice for a single device preview.

Connecting UI Elements to Code (Outlets and Actions)

Section titled “Connecting UI Elements to Code (Outlets and Actions)”

To interact with these UI elements in Swift, we need to create connections:

  1. Open the Assistant Editor: With Main.storyboard active, click the Assistant Editor button (two overlapping circles icon in the toolbar) or press Option-Command-Return. This should open ViewController.swift alongside your storyboard.
  2. Create Outlets for input and output elements:
    • For the Text Field: Control-drag from the UITextField in the storyboard to your ViewController.swift file, just below the class ViewController... line. In the popup, ensure ‘Connection’ is ‘Outlet’, provide a ‘Name’ (e.g., ageTextField), and click ‘Connect’.
    • For the Result Label: Control-drag from the result UILabel to ViewController.swift. Create an outlet named resultLabel.
  3. Create an Action for the Button:
    • Control-drag from the UIButton (‘Calculate Age’) to ViewController.swift, placing it inside the class curly braces, typically below viewDidLoad() or other outlets. In the popup:
      • Set ‘Connection’ to ‘Action’.
      • Give it a ‘Name’ (e.g., calculateButtonTapped).
      • Ensure ‘Type’ is UIButton (or Any if you prefer).
      • Click ‘Connect’.

Your ViewController.swift should now have lines like these (order may vary):

import UIKit
class ViewController: UIViewController {
@IBOutlet weak var ageTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Initial setup, e.g., clear result label
resultLabel.text = ""
}
@IBAction func calculateButtonTapped(_ sender: UIButton) {
// Logic will go here
}
}

Now, let’s add the calculation logic inside the calculateButtonTapped action method.

@IBAction func calculateButtonTapped(_ sender: UIButton) {
// 1. Get text from the text field
guard let ageText = ageTextField.text, !ageText.isEmpty else {
resultLabel.text = "Please enter an age."
return
}
// 2. Convert text to an integer
guard let humanYears = Int(ageText) else {
resultLabel.text = "Invalid number entered."
return
}
// 3. Perform the calculation (e.g., 1 human year = 7 dog years for simplicity)
// The original tutorial used a multiplier of 8.
let dogAgeMultiplier = 7 // Or use 8 to match original tutorial if preferred
let calculatedDogYears = humanYears * dogAgeMultiplier
// 4. Display the result in the label
resultLabel.text = "Your dog is \(calculatedDogYears) in dog years!"
// Optional: Dismiss keyboard
ageTextField.resignFirstResponder()
}

Tip: Swift doesn’t require semicolons at the end of lines if each statement is on its own line. The code uses guard let for safe unwrapping of optionals (like ageTextField.text) and for early exit if input is invalid. String interpolation (\(...)) is used to create the output string.

Run your application. Enter a number in the text field and tap the ‘Calculate Age’ button. The result should appear in the label. Try entering non-numeric text or leaving it empty to see the error messages.

If the keyboard doesn’t appear when you tap the text field in the simulator, you might need to enable it: With the simulator active, go to the menu I/O > Keyboard > Toggle Software Keyboard (or Command-K).

You’ve now built an interactive app! This foundation of UI elements, outlets, actions, and basic logic is key to most iOS applications. In the next chapters, we’ll explore more advanced Swift concepts and iOS features.