xcode Swift 4 添加手势:覆盖 vs @objc

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44867038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:06:12  来源:igfitidea点击:

Swift 4 add gesture: override vs @objc

iosobjective-cswiftxcodeswift4

提问by M4CH1N3

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:

但是,在 Swift 4 中,我的编译器给了我以下错误:

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.

建议添加@objc 以将此实例方法公开给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.

实现这一点的另一种选择(仅通过代码)是覆盖该touchesBegan()函数并使用它来处理点击。

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?

我正在尝试以“Swift”方式执行此操作,而无需引入 Obj-C。是否有一种纯粹的 Swift 方法可以在不使用 @objc 的情况下添加这个点击手势?或者这是添加此点击手势的正常和预期方式?

回答by Ali Beadle

Using @objchere is the normal and intended way.

@objc在这里使用是正常的和预期的方式。

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 @objcis doing.

底层的手势识别器代码是用 Objective-C 编写的,所以你需要让你的选择器可以从 Objective-C 调用,这就是全部@objc

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

您的替代技术仍然使用 Objective C-API,但在没有选择器的情况下与它们交互,因此它不太明显。