I added UITapGestureRecognizer
to my UIView
. But I don't understand why I have to use @objc
to use UITapGestureRecognizer
.
In particular, the difference between Selector?
and #selector
is too confusing.
And I didn't see an explanation using @objc
in the official document of the Apple developer.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let viw = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
viw.center = self.view.center
viw.backgroundColor = UIColor.black
self.view.addSubview(viw)
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
viw.addGestureRecognizer(tap)
}
@objc func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .ended {
print(1)
}
}
}
I think this is an old way. If there is an up-to-date way to add UITapGestureRecognizer
to UIView
, I would like to know that.
Why @objc ?
If you are using any class selectors which is basically written in Objective-C
than you need to add @objc
before that function so that UITapGestureRecognizer
class can revert back with proper event.
If you are not adding @objc
before your gesture handler function compiler will throw error as mention below :
Argument of '#selector' refers to instance method 'handleTap()' that is not exposed to Objective-C
It clearly says that you haven't exposed your handle for Objective-C
.
Apple Officially link for Language Interoperability
https://developer.apple.com/documentation/swift#2984801
Also check this link for more info on
Use runtime Obj C features in Swift
Hope you can get your answer form above explanation!