简体   繁体   English

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

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. 我试图以“Swift”的方式做到这一点,而不必带入Obj-C。 Is there a pure Swift way to add this tap gesture without using @objc? 有没有纯粹的Swift方式来添加这个轻击手势而不使用@objc? Or is that the normal and intended way of adding this tap gesture? 或者这是添加此点按手势的正常和预期方式?

Using @objc here 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 @objc is 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,但是在没有选择器的情况下与它们交互,因此它不那么明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM