且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Swift中将参数传递给选择器

更新时间:2022-02-04 00:50:42

看起来你误解了一些事情。

It looks like you're misunderstanding a couple of things.

使用目标/操作,函数签名必须具有某种形式......

When using target/action, the function signature has to have a certain form…

func doSomething(sender: Any)

func doSomething(sender: Any, forEvent event: UIEvent)

其中......


sender 参数是发送操作消息的控制对象。

The sender parameter is the control object sending the action message.

在您的情况下,发件人是 UITapGestureRecognizer

In your case, the sender is the UITapGestureRecognizer

此外, #s elector()应该包含func签名,并且不包含传递的参数。所以...

Also, #selector() should contain the func signature, and does NOT include passed parameters. So for…

func handleTap(sender: UIGestureRecognizer) {

}

你应该......

let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))

假设func和手势在一个视图控制器中,其中 modelObj 是属性/ ivar,没有必要用手势识别器传递它,你可以参考在 handleTap

Assuming the func and the gesture are within a view controller, of which modelObj is a property / ivar, there's no need to pass it with the gesture recogniser, you can just refer to it in handleTap