Fix: Cannot Pass Custom Arguments to Selector in Swift UIKit

Written by

in

Quick answer: Swift @objc selectors only accept (sender: Any) or (sender: Any, event: UIEvent) signatures. To pass custom data, store it on the gesture recognizer’s view, use objc_setAssociatedObject, or wrap the action in a closure-based helper.

Why this happens

The Objective‑C runtime that powers @objc selectors only understands a fixed set of method signatures for target‑action: no parameters, a single sender: Any, or sender: Any plus event: UIEvent. When you write #selector(handleTap(modelObj:)) the compiler sees a parameter of your custom Model type, which has no representation in the Objective‑C type system, so it emits “Method cannot be marked @objc because the type of the parameter cannot be represented in Objective‑C.”

Gesture recognizers always call their action with themselves as the sender. The runtime cannot magically inject an arbitrary model object into that call. You must move the data to a place the selector can reach: the view the recognizer is attached to, an associated object on the recognizer, or a closure wrapper that captures the context.

How to fix it

1. Read the model from the gesture recognizer’s view (simplest)

If the view that owns the recognizer already has a reference to the model—e.g. a UIImageView inside a cell that knows its PointOfInterest—cast sender.view and pull the data from there.

class MapPinView: UIImageView {
    var pointOfInterest: PointOfInterest?
}

// Setup
let pinView = MapPinView()
pinView.pointOfInterest = poi
let tap = UITapGestureRecognizer(target: self, action: #selector(handlePinTap(_:)))
pinView.addGestureRecognizer(tap)
pinView.isUserInteractionEnabled = true

@objc func handlePinTap(_ sender: UITapGestureRecognizer) {
    guard let pin = sender.view as? MapPinView,
          let poi = pin.pointOfInterest else { return }
    // Use poi
}

2. Attach the model to the gesture recognizer with associated objects

When you cannot subclass the view, use objc_setAssociatedObject to hang any Any value on the recognizer itself. This works for any UIGestureRecognizer subclass.

import ObjectiveC.runtime

private var modelKey: UInt8 = 0

extension UIGestureRecognizer {
    var associatedModel: Any? {
        get { objc_getAssociatedObject(self, &modelKey) }
        set { objc_setAssociatedObject(self, &modelKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
    }
}

// Setup
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
tap.associatedModel = myModelObj
imageView.addGestureRecognizer(tap)

@objc func handleTap(_ sender: UITapGestureRecognizer) {
    guard let model = sender.associatedModel as? MyModel else { return }
    // Use model
}

3. Use a closure‑based wrapper (modern, type‑safe)

Wrap the target‑action in a small helper that captures the model in a closure, then forwards to your real handler. This avoids @objc signature limits entirely.

final class ClosureAction {
    let handler: (UIGestureRecognizer) -> Void
    init(_ handler: @escaping (UIGestureRecognizer) -> Void) { self.handler = handler }
    @objc func invoke(_ sender: UIGestureRecognizer) { handler(sender) }
}

extension UIGestureRecognizer {
    func addAction(_ action: @escaping (UIGestureRecognizer) -> Void) {
        let wrapper = ClosureAction(action)
        addTarget(wrapper, action: #selector(ClosureAction.invoke(_:)))
        // Keep wrapper alive for the recognizer's lifetime
        objc_setAssociatedObject(self, "\(Unmanaged.passUnretained(wrapper).toOpaque())", wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}

// Usage
let tap = UITapGestureRecognizer()
tap.addAction { [weak self] _ in
    self?.handlePinTap(model: myModelObj)
}
imageView.addGestureRecognizer(tap)

func handlePinTap(model: MyModel) { /* … */ }

4. Subclass the control (for UIControl subclasses only)

If the target is a UIButton or other UIControl, subclass it and add stored properties. This is the pattern shown in the second Stack Overflow answer.

class ModelButton: UIButton {
    var payload: Any?
}

let btn = ModelButton(type: .system)
btn.payload = myModelObj
btn.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)

@objc func buttonTapped(_ sender: ModelButton) {
    guard let model = sender.payload as? MyModel else { return }
    // Use model
}

How to prevent it

  • Remember the fixed selector signatures: (), (sender: Any), (sender: Any, event: UIEvent).
  • Keep model data on the view hierarchy (view, cell, view controller) rather than trying to pass it through the selector.
  • Prefer closure‑based APIs (UIAction, addAction(_:) on iOS 14+) for new code; they capture context naturally.
  • If you must support older iOS, centralise the associated‑object helper in a shared extension.

FAQ

Can I use #selector with a Swift generic method?

No. @objc methods cannot be generic because the Objective‑C runtime has no representation for Swift generics. Use a concrete type or Any and cast inside the handler.

Why does UITapGestureRecognizer send itself as the sender?

That is the defined target‑action contract for gesture recognizers. The sender is the recognizer, so you can query its state, location(in:), view, etc.

Is there a SwiftUI equivalent of this problem?

SwiftUI uses closures (onTapGesture { model in … }) so you capture the model directly. The selector limitation only appears when bridging to UIKit or AppKit.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.