Swift希望#selector的参数暴露给Objective-C [英] Swift wants argument of #selector to be exposed to Objective-C

查看:883
本文介绍了Swift希望#selector的参数暴露给Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swift项目,我想在UIButton的tap事件中附加一个方法。我有以下代码:

I have a Swift project where I want to attach a method to a UIButton's tap event. I have the following code:

class MyClass {
  let myButton = UIButton(frame: CGRectMake(50, 50, 100, 50))
  init() {
    myButton.addTarget(self, #selector(self.didTap(_:)), forControlEvents: .TouchUpInside)
  }

  func didTap(sender: UIButton) {
    print("Tapped")
  }
}

XCode突出显示我的 addTarget 行并说:

XCode highlights my addTarget line and says:

Argument of '#selector' refers to a method that is not exposed to Objective-C

如果我将 @objc 前缀添加到我的 func didTap ,就像它建议那样一切正常。

If I add the @objc prefix to my func didTap like it suggests then everything works fine.

我的构建设置中是否启用了导致此奇怪行为的内容?

Do I have something enabled in my build settings which is causing this strange behaviour?

PS。我在7.3.1中得到了这种行为。但是如果我在7.2.1中尝试这个,它不接受 #selector(method(_:))语法,并且选择器(方法 :)工作正常。

PS. I get this behaviour in 7.3.1. But if I try this in 7.2.1 it doesn't accept the #selector(method(_:)) syntax, and Selector("method:") works fine.

推荐答案

选择器是Objective-C的一个特性,只能是与暴露于动态Obj-C运行时的方法一起使用。你不能有一个纯粹的Swift方法的选择器。

Selectors are a feature of Objective-C and can only be used with methods that are exposed to the dynamic Obj-C runtime. You can't have a selector to a pure Swift method.

如果你的类继承自 NSObject 那么它的公开方法自动暴露给Obj-C。由于您的类不继承自 NSObject ,您必须使用 @objc 属性来指示您希望此方法暴露到Obj-C,以便可以用Obj-C选择器调用它。

If your class inherits from NSObject then its public methods are exposed to Obj-C automatically. Since your class does not inherit from NSObject you have to use the @objc attribute to indicate that you want this method exposed to Obj-C so that it may be called with an Obj-C selector.

#selector()是Swift 2.2中的新语法。它允许编译器检查您尝试使用的选择器是否确实存在。旧语法已弃用,将在Swift 3.0中删除。

#selector() is the new syntax in Swift 2.2. It allows the compiler to check that the selector you're trying to use actually exists. The old syntax is deprecated and will be removed in Swift 3.0.

这篇关于Swift希望#selector的参数暴露给Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆