简体   繁体   English

Swift:将参数传递给选择器

[英]Swift: Passing a parameter to selector

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 tag has 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? 如何将参数传递给选择器?

#selector describes method signature only. #selector仅描述方法签名。 In your case the correct way to initialize the selector is 在您的情况下,初始化选择器的正确方法是

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

Timer has the common target-action mechanism. Timer具有共同的目标 - 动作机制。 Target is usually self and action is a method that takes one parameter sender: Timer . Target通常是self,action是一个带有一个参数sender: Timer的方法sender: Timer You should save additional data to userInfo dictionary, and extract it from sender parameter in the method: 您应该将其他数据保存到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)

You cannot pass a custom parameter through a Timer action. 您无法通过Timer操作传递自定义参数。

Either

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

or 要么

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

is supported, nothing else. 是支持,没有别的。

To pass custom parameters use the userInfo dictionary. 要传递自定义参数,请使用userInfo字典。

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

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