Bird
Raised Fist0
iOS Swiftmobile~20 mins

Button and action handling in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Button Screen
This screen shows a button. When the user taps the button, a label updates to say 'Button tapped!'.
Target UI
---------------------
|                   |
|    [Tap Me]       |
|                   |
|                   |
|                   |
|   Label:          |
|                   |
---------------------
Add a UIButton centered horizontally near the top with the title 'Tap Me'.
Add a UILabel below the button to show messages.
When the button is tapped, update the label text to 'Button tapped!'.
Use Auto Layout constraints for positioning.
Ensure accessibility labels for the button and label.
Starter Code
iOS Swift
import UIKit

class SimpleButtonViewController: UIViewController {

    let button = UIButton(type: .system)
    let messageLabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // TODO: Configure button

        // TODO: Configure label

        // TODO: Add button and label to view

        // TODO: Setup Auto Layout constraints

        // TODO: Add button action handler
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import UIKit

class SimpleButtonViewController: UIViewController {

    let button = UIButton(type: .system)
    let messageLabel = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Configure button
        button.setTitle("Tap Me", for: .normal)
        button.accessibilityLabel = "Tap Me Button"
        button.translatesAutoresizingMaskIntoConstraints = false

        // Configure label
        messageLabel.text = ""
        messageLabel.textAlignment = .center
        messageLabel.accessibilityLabel = "Message Label"
        messageLabel.translatesAutoresizingMaskIntoConstraints = false

        // Add subviews
        view.addSubview(button)
        view.addSubview(messageLabel)

        // Setup Auto Layout constraints
        NSLayoutConstraint.activate([
            button.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),

            messageLabel.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 20),
            messageLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            messageLabel.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 20),
            messageLabel.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20)
        ])

        // Add button action handler
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    }

    @objc func buttonTapped() {
        messageLabel.text = "Button tapped!"
    }
}

We create a UIButton and UILabel as properties. In viewDidLoad, we set the button title to 'Tap Me' and add an accessibility label for screen readers. The label starts empty and is centered below the button. We use Auto Layout constraints to position the button near the top center and the label below it with some spacing. The button's touchUpInside event triggers the buttonTapped method, which updates the label text to 'Button tapped!'. This simple interaction shows how to handle button taps and update UI elements in Swift.

Final Result
Completed Screen
---------------------
|                   |
|    [Tap Me]       |
|                   |
|                   |
|                   |
|   Button tapped!   |
|                   |
---------------------
When the user taps the 'Tap Me' button, the label text changes from empty to 'Button tapped!'.
Stretch Goal
Add a second button labeled 'Reset' below the label that clears the label text when tapped.
💡 Hint
Create another UIButton, add it below the label with Auto Layout, and add a target action that sets the label text to an empty string.

Practice

(1/5)
1. What is the main purpose of a UIButton in an iOS app?
easy
A. To let users tap and trigger actions
B. To display static text only
C. To store data persistently
D. To manage app navigation automatically

Solution

  1. Step 1: Understand UIButton role

    A UIButton is a UI element that users can tap to perform an action.
  2. Step 2: Compare options with UIButton purpose

    Only To let users tap and trigger actions describes this interaction purpose correctly.
  3. Final Answer:

    To let users tap and trigger actions -> Option A
  4. Quick Check:

    UIButton = user tap action [OK]
Hint: Buttons are for user taps triggering actions [OK]
Common Mistakes:
  • Confusing buttons with labels
  • Thinking buttons store data
  • Assuming buttons handle navigation automatically
2. Which of the following is the correct way to add an action to a UIButton in Swift?
easy
A. button.onTap = buttonTapped()
B. button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
C. button.addAction(#selector(buttonTapped))
D. button.action = #selector(buttonTapped)

Solution

  1. Step 1: Recall UIButton action syntax

    The correct method is addTarget(_:action:for:) with #selector for the method.
  2. Step 2: Match syntax with options

    Only button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) uses the correct method and parameters.
  3. Final Answer:

    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) -> Option B
  4. Quick Check:

    addTarget + #selector + .touchUpInside = correct [OK]
Hint: Use addTarget with #selector and .touchUpInside [OK]
Common Mistakes:
  • Using nonexistent addAction method
  • Assigning action directly without addTarget
  • Calling the selector method instead of referencing it
3. Given the code below, what happens when the button is tapped?
let button = UIButton()
button.addTarget(self, action: #selector(showMessage), for: .touchUpInside)

@objc func showMessage() {
    print("Button was tapped")
}
medium
A. The app crashes due to missing button title
B. Nothing happens because the method is missing @objc
C. The message "Button was tapped" is printed to the console
D. The button changes color automatically

Solution

  1. Step 1: Check action method annotation

    The method showMessage is marked with @objc, so it can be called by the button.
  2. Step 2: Understand button tap behavior

    When tapped, the button triggers showMessage, which prints the message.
  3. Final Answer:

    The message "Button was tapped" is printed to the console -> Option C
  4. Quick Check:

    @objc method called on tap = print message [OK]
Hint: @objc method runs on button tap printing message [OK]
Common Mistakes:
  • Forgetting @objc on action method
  • Expecting UI changes without code
  • Confusing button title with action effect
4. Identify the error in this code snippet that prevents the button action from working:
let button = UIButton()
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

func buttonPressed() {
    print("Pressed")
}
medium
A. The button title is not set
B. The button is not added to the view
C. The selector syntax is incorrect
D. The action method is missing the @objc attribute

Solution

  1. Step 1: Check method declaration for selector

    Methods used with #selector must be marked @objc to be visible to Objective-C runtime.
  2. Step 2: Verify other code parts

    While adding button to view and title are important, they don't prevent action from being called.
  3. Final Answer:

    The action method is missing the @objc attribute -> Option D
  4. Quick Check:

    @objc missing on action method = no call [OK]
Hint: Action methods need @objc to be called by button [OK]
Common Mistakes:
  • Ignoring @objc requirement
  • Thinking button must have title for action
  • Assuming selector syntax is wrong when it's correct
5. You want to create a button that changes its title to "Clicked" when tapped. Which code snippet correctly implements this behavior?
let button = UIButton()
button.setTitle("Tap me", for: .normal)
button.addTarget(self, action: #selector(changeTitle), for: .touchUpInside)

@objc func changeTitle() {
    // What goes here?
}
hard
A. self.button.setTitle("Clicked", for: .normal)
B. button.setTitle("Clicked", for: .normal)
C. button.title = "Clicked"
D. changeTitle.title = "Clicked"

Solution

  1. Step 1: Understand scope of button variable

    The button variable is declared outside the method, so inside changeTitle() you must reference it properly, usually as self.button.
  2. Step 2: Use correct method to change title

    UIButton's title is changed using setTitle(_:for:) method, not by assigning to a property.
  3. Final Answer:

    self.button.setTitle("Clicked", for: .normal) -> Option A
  4. Quick Check:

    Use self.button.setTitle to update title [OK]
Hint: Use self.button.setTitle("Clicked", for: .normal) inside action [OK]
Common Mistakes:
  • Trying to assign title directly
  • Using button without self when needed
  • Calling setTitle on wrong object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard