Skip to content
Prepare to Grow

UIKit Development

Target–Action, Delegates, and User Interaction

Connect user intent to application behavior with actions, delegates, gestures, and safe ownership boundaries.

Intermediate6 min read2 guided activities

Before you begin

What you will understand

  • Use UIAction and target–action for controls.
  • Design weak delegate relationships.
  • Add gestures only when semantic controls do not fit.
  • Prevent duplicated actions and retain cycles.
01

Learning stage

Concept Explanation

Controls turn physical interaction into semantic events. You can connect them to selector-based target–action or attach UIAction closures. The handler should translate the event into an application intention—save, retry, select—not contain an entire workflow inside the visual component.

Delegation models an ongoing one-to-one collaboration. The delegating object defines a protocol, holds a weak delegate when the delegate owns or outlives it, and reports meaningful events. Data source protocols answer questions; delegate protocols commonly report choices or customize behavior.

Gesture recognizers are appropriate for spatial gestures on views, such as pinch or pan. Do not replace buttons with gestures simply for styling. Consider competition between gestures, touch cancellation, keyboard and pointer input, accessibility actions, and whether repeated configuration might register the same handler twice.

  • Target–action: sends a control event to a handler.
  • UIAction: closure-based semantic action.
  • Delegate: receives events or provides customization through a protocol.
  • Data source: supplies data requested by a view.
  • Gesture recognizer: interprets a stream of touches as a gesture.
  • Weak reference: prevents an ownership cycle in a callback relationship.
02

Learning stage

Syntax & Examples

A reusable rating view reports a semantic choice without owning the feature workflow.

RatingView.swiftswift
protocol RatingViewDelegate: AnyObject {
  func ratingView(_ view: RatingView, didSelect rating: Int)
}

final class RatingView: UIStackView {
  weak var delegate: RatingViewDelegate?

  override init(frame: CGRect) {
    super.init(frame: frame)
    axis = .horizontal
    spacing = 8

    for rating in 1...5 {
      var config = UIButton.Configuration.plain()
      config.image = UIImage(systemName: "star")
      let button = UIButton(configuration: config)
      button.accessibilityLabel = "Rate (rating) out of 5"
      button.addAction(UIAction { [weak self] _ in
        guard let self else { return }
        self.delegate?.ratingView(self, didSelect: rating)
      }, for: .primaryActionTriggered)
      addArrangedSubview(button)
    }
  }

  required init(coder: NSCoder) { fatalError("Use init(frame:)") }
}
The buttons remain semantic controls and the weak delegate receives a domain-level rating event.
03

Learning stage

Real-World Usage

Connect the UIKit concept to complete, maintainable application features.

  • Report selection from reusable components to a screen controller.
  • Use UIAction for local button behavior.
  • Coordinate text fields through their delegate.
  • Add swipe, pan, or pinch behavior where direct manipulation is central.
04

Learning stage

Common Mistakes

Identify lifecycle, ownership, identity, layout, accessibility, and user-experience risks.

  • Capturing a controller strongly in a long-lived action closure.
  • Declaring an owning delegate property and creating a cycle.
  • Registering actions repeatedly during cell configuration.
  • Using tap gestures on labels instead of buttons.
  • Exposing low-level touch coordinates when callers need a semantic event.
05

Learning stage

Practice Exercises

Build the behavior in a small Xcode project and inspect it across realistic states.

Activity 1

Design a filter delegate

Create a filter chip view that reports the selected filter using a class-bound protocol and weak delegate.

Hint: The event should communicate the selected value, not which pixel was tapped.

Activity 2

Choose the interaction mechanism

For save, card selection, image zoom, text editing, and list data, choose control action, delegate, gesture, or data source and justify each.

Hint: Begin with semantic intent and accessibility.

06

Learning stage

Knowledge Check

Answer each question before revealing the explanation.

QUESTION 1

Why are delegate references often weak?

  1. A.To avoid an ownership cycle when the delegate owns the delegating object
  2. B.To make methods faster
  3. C.To enable Auto Layout
  4. D.To avoid protocols
Reveal answer

To avoid an ownership cycle when the delegate owns the delegating object

The relationship communicates events but usually should not extend the delegate's lifetime.

QUESTION 2

When is a gesture recognizer preferable to a button?

Reveal answer

When interpreting a spatial gesture such as pan, pinch, rotation, or a tap on non-control content is central to the interaction.

A standard button remains better for a normal semantic action.

07

Learning stage

Interview Preparation

Explain the design in terms of lifecycle, identity, ownership, system behavior, and trade-offs.

How do you choose between target–action, a closure, and delegation?

Short answer: Use control actions for discrete UI events, a focused closure for local one-off callbacks, and delegation for a continuing structured relationship.

Explore the detailed answer

I consider semantics, lifetime, multiplicity, and ownership. UIAction is concise for control events. A closure works for one focused callback if capture behavior is clear. A class-bound weak delegate scales to multiple related events and customization points without coupling the component to a feature controller.

Possible follow-ups

  • • How can actions create retain cycles?
  • • What distinguishes a delegate from a data source?
08

Learning stage

Key Takeaways

Interaction APIs should translate input into semantic intent while preserving accessibility and clear object lifetimes.

  • Prefer controls for semantic actions.
  • Use UIAction or target–action for control events.
  • Keep delegates weak when ownership flows the other way.
  • Use gestures for genuinely spatial interaction.
  • Register handlers once and audit closure captures.