在Swift中使用选择器的正确方法 [英] Proper way to use selectors in Swift

查看:52
本文介绍了在Swift中使用选择器的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式创建视图,并添加一个函数,以便该操作响应UIControlEvents.TouchUpInside事件:

I'm creating a view programatically, and adding a function so the action responds to the UIControlEvents.TouchUpInside event:

button.addTarget(self, action: action, forControlEvents: 
UIControlEvents.TouchUpInside)

因此,通过进入文档,我将该动作添加为选择器:

So, by going into the documentation I've added this action as a selector:

#selector(ViewController.onRegularClick)

XCode然后投诉:

XCode then complaints about:

#selector的参数是指未公开给您的方法Objective-C

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

因此,我必须使用以下命令设置处理程序功能:

So I have to set up the handler function with:

@objc func onRegularClick(sender: UIButton)

有人可以指导我阅读文档,或者甚至对以下内容进行简短的解释,以使此菜鸟指向正确的方向吗?

Can some one please put this noob on the right direction by guiding me to the documentation, or even give a short explanation, on:

  1. 为什么我不能再简单地将函数名称String传递给操作了?
  2. 按照Swift方式实现此目标的正确方法是什么?使用Selector类?
  3. 为什么我们需要传递@objc关键字以及它如何影响功能?

谢谢!

推荐答案

  1. 为什么我不能再简单地将函数名称String传递给操作了?

已不建议使用用于选择器的字符串,现在您应该编写 #selector(methodName)而不是"methodName" .如果methodName()方法不存在,则会出现编译错误-在编译时消除了另一类错误.这对于字符串是不可能的.

Using strings for selectors has been deprecated, and you should now write #selector(methodName)instead of "methodName". If the methodName() method doesn't exist, you'll get a compile error – another whole class of bugs eliminated at compile time. This was not possible with strings.

  1. 按照Swift方式实现此目标的正确方法是什么?使用Selector类?

您以正确的方式做到了:

You did it the right way:

button.addTarget(self,action:#selector(ClassName.methodName(_ :)),forControlEvents:UIControlEvents.TouchUpInside)

  1. 为什么我们需要传递@objc关键字以及它如何影响功能?

在Swift中,通常的方法是在编译时绑定方法的调用和方法的主体(就像C和C ++一样).目标C在运行时执行.因此,在Objective C中,您可以执行某些在Swift中无法完成的事情-例如,可以在运行时交换方法的实现(称为方法混乱).Cocoa旨在与Objective C方法一起使用,这就是为什么您必须通知编译器您的Swift方法应以类似于ObjectiveC的样式进行编译的原因.如果您的类继承了NSObject,即使没有@objc关键字,它也会被编译成类似ObjC的样式.

In Swift the normal approach is to bind method's calls and method's bodies at compile time (like C and C++ do). Objective C do it at run time. So in Objective C you can do some things that are not possible in Swift - for example it is possible to exchange method's implementation at run time (it is called method swizzling). Cocoa was designed to work with Objective C approach and this is why you have to inform compiler that your Swift method should be compiled ObjectiveC-like style. If your class inherits NSObject it will be compiled ObjC-like style even without @objc keyword.

这篇关于在Swift中使用选择器的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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