Bird
0
0

Which of the following is the correct syntax to assign an action method to a UIButton for the .touchUpInside event in Swift?

easy📝 Syntax Q3 of 15
iOS Swift - SwiftUI Basics
Which of the following is the correct syntax to assign an action method to a UIButton for the .touchUpInside event in Swift?
Abutton.addAction(#selector(buttonPressed), for: .touchUpInside)
Bbutton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
Cbutton.setAction(#selector(buttonPressed), for: .touchUpInside)
Dbutton.addTarget(self, action: buttonPressed, for: .touchUpInside)
Step-by-Step Solution
Solution:
  1. Step 1: Use addTarget(_:action:for:) method

    This method is used to add a target and action for a control event.
  2. Step 2: Use #selector syntax for the action

    The action parameter requires a selector, which is specified using #selector(methodName).
  3. Final Answer:

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

    Correct method and selector syntax used [OK]
Quick Trick: Use addTarget with #selector for button actions [OK]
Common Mistakes:
  • Using addAction instead of addTarget
  • Passing method name without #selector
  • Using setAction which doesn't exist

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes