Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 add gesture: override vs @objc

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?

like image 333
M4CH1N3 Avatar asked Jul 02 '17 02:07

M4CH1N3


1 Answers

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.

like image 68
Ali Beadle Avatar answered Nov 15 '22 22:11

Ali Beadle