7

I'm looking to add a gesture to my view as follows:

    override func viewDidLoad() {
    super.viewDidLoad()

    < blah blah blah >

    // Add tap gesture
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    myView.addGestureRecognizer(tap)
}

However, in Swift 4 my compiler is giving me the following error:

Argument of '#selector' refers to instance method 'handleTap()' that is not exposed to Objective-C

The suggestion is to add @objc to expose this instance method to Objective-C.

The other option to implement this (through code only) would be to override the touchesBegan() function and use that to handle the tap.

I am trying to do this the 'Swift' way without having to bring in Obj-C. Is there a pure Swift way to add this tap gesture without using @objc? Or is that the normal and intended way of adding this tap gesture?

M4CH1N3
  • 117
  • 1
  • 5
  • Possible duplicate of [How can I deal with @objc inference deprecation with #selector() in Swift 4?](https://stackoverflow.com/questions/44390378/how-can-i-deal-with-objc-inference-deprecation-with-selector-in-swift-4) – LinusGeffarth Sep 14 '17 at 21:30

1 Answers1

21

Using @objc here is the normal and intended way.

The underlying gesture recogniser code is written in Objective-C so you need to make your selector callable from Objective-C and that is all @objc is doing.

Your alternative technique is still using Objective C-APIs, but interacting with them without selectors so it is just less visible.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Ali Beadle
  • 4,486
  • 3
  • 30
  • 55
  • 1
    Good answer ;) I would only add that this change was implemented by the [Limiting @objc inference proposal](https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md) in Swift 4. – Paulo Mattos Jul 06 '17 at 20:23