为什么在 "UITapGestureRecognizer" 中使用 @objc?

Why @objc in "UITapGestureRecognizer"?

我将 UITapGestureRecognizer 添加到我的 UIView。但是不明白为什么要用@objc才能用UITapGestureRecognizer.

特别是Selector?#selector的区别太混乱了

而且我没有在 official document of the Apple developer 中看到使用 @objc 的解释。

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)
        }
    }
}

我认为这是一种旧方法。如果有最新的方法可以将 UITapGestureRecognizer 添加到 UIView,我想知道。

为什么@objc?

如果您使用的 class 选择器基本上是用 Objective-C 编写的,那么您需要在该函数之前添加 @objc 以便 UITapGestureRecognizer class 可以通过适当的事件恢复。

如果您没有在手势处理函数编译器之前添加 @objc,编译器将抛出如下所述的错误:

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

它清楚地表明你还没有暴露你的句柄Objective-C

Apple 正式 link 语言互操作性

https://developer.apple.com/documentation/swift#2984801

另请查看此 link 以获取有关

的更多信息

Use runtime Obj C features in Swift

希望你能在上面的解释中得到你的答案!