Swift 4 add gesture: override vs @objc

I want to add a gesture to my opinion 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 tells me the following error:

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

It is suggested to add @objc to show this method of the Objective-C instance.

Another implementation option (with code only) would be to override the touchesBegan() function and use it to handle the tap.

I try to do this "Swift" without resorting to Obj-C. Is there a clean Swift way to add this tap gestures without using @objc? Or is this the usual and supposed way to add this tap gestures?

+5
ios objective-c xcode swift swift4
Jul 02 '17 at 2:46 on
source share
1 answer

Using @objc here is the normal and intended way.

The main code of the gesture recognizer is written in Objective-C, so you need to make your selector callable from Objective-C and that is what @objc does.

Your alternate method still uses the Objective C-API, but interacts with them without selectors, so it is less noticeable.

+17
Jul 02 '17 at 5:45
source share



All Articles