Bird
0
0

Given the code below, what happens when the button is tapped?

medium📝 Predict Output Q13 of 15
iOS Swift - SwiftUI Basics
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")
}
AThe app crashes due to missing button title
BNothing happens because the method is missing @objc
CThe message "Button was tapped" is printed to the console
DThe button changes color automatically
Step-by-Step Solution
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]
Quick Trick: @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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes