ios Swift:将参数传递给选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41987324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:07:12  来源:igfitidea点击:

Swift: Passing a parameter to selector

iosswift3

提问by user1107173

Using Swift 3, Xcode 8.2.1

使用 Swift 3,Xcode 8.2.1

Method:

方法:

func moveToNextTextField(tag: Int) {
   print(tag)
}

The lines below compile fine, but taghas an uninitialized value:

下面的行编译正常,但tag有一个未初始化的值:

let selector = #selector(moveToNextTextField)
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: selector, userInfo: nil, repeats: false)

However, I need to pass a parameter. Below fails to compile:

但是,我需要传递一个参数。下面编译失败:

let selector = #selector(moveToNextTextField(tag: 2))

Swift Compile Error:
Argument of #selector does not refer to an @objc method, property, or initializer.

How can I pass an argument to a selector?

如何将参数传递给选择器?

回答by hybridcattt

#selectordescribes method signature only. In your case the correct way to initialize the selector is

#selector仅描述方法签名。在您的情况下,初始化选择器的正确方法是

let selector = #selector(moveToNextTextField(tag:))

Timer has the common target-action mechanism. Target is usually self and action is a method that takes one parameter sender: Timer. You should save additional data to userInfodictionary, and extract it from senderparameter in the method:

定时器具有通用的目标-动作机制。目标通常是 self ,而 action 是一种接受一个参数的方法sender: Timer。您应该将其他数据保存到userInfo字典中,并从sender方法中的参数中提取它:

func moveToNextTextField(sender: Timer) {
   print(sender.userInfo?["tag"])
}
...
let selector = #selector(moveToNextTextField(sender:))
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: selector, userInfo: ["tag": 2], repeats: false)

回答by vadian

You cannot pass a custom parameter through a Timeraction.

您不能通过操作传递自定义参数Timer

Either

任何一个

#selector(moveToNextTextField)
...
func moveToNextTextField()

or

或者

#selector(moveToNextTextField(_:))
...
func moveToNextTextField(_ timer : Timer)

is supported, nothing else.

支持,没有别的。

To pass custom parameters use the userInfodictionary.

要传递自定义参数,请使用userInfo字典。