Swift 4 添加手势:覆盖 vs @objc [英] 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)
}
但是,在 Swift 4 中,我的编译器给了我以下错误:
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
建议添加@objc,将这个实例方法暴露给Objective-C.
The suggestion is to add @objc to expose this instance method to Objective-C.
实现此功能的另一个选项(仅通过代码)是覆盖 touchesBegan()
函数并使用它来处理点击.
The other option to implement this (through code only) would be to override the touchesBegan()
function and use that to handle the tap.
我正在尝试以Swift"方式执行此操作,而无需引入 Obj-C.是否有一种纯粹的 Swift 方法可以在不使用 @objc 的情况下添加这个点击手势?或者这是添加此点击手势的正常和预期方式?
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?
推荐答案
使用 @objc
这里是正常的和预期的方式.
Using @objc
here is the normal and intended way.
底层的手势识别器代码是用 Objective-C 编写的,所以你需要让你的选择器可以从 Objective-C 调用,这就是 @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 @objc
is doing.
您的替代技术仍然使用 Objective C-API,但在没有选择器的情况下与它们交互,因此它不太明显.
Your alternative technique is still using Objective C-APIs, but interacting with them without selectors so it is just less visible.
这篇关于Swift 4 添加手势:覆盖 vs @objc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!