Swift:将参数传递给选择器 [英] Swift: Passing a parameter to selector
问题描述
使用Swift 3,Xcode 8.2.1
Using Swift 3, Xcode 8.2.1
方法:
func moveToNextTextField(tag: Int) {
print(tag)
}
下面的行编译正常,但标记
有一个未初始化的值:
The lines below compile fine, but tag
has an uninitialized value:
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
仅描述方法签名。在你的情况下,初始化选择器的正确方法是
#selector
describes method signature only. In your case the correct way to initialize the selector is
let selector = #selector(moveToNextTextField(tag:))
Timer具有共同的目标 - 动作机制。 Target通常是self,action是一个带有一个参数 sender:Timer
的方法。您应该将其他数据保存到 userInfo
字典,并从方法中的 sender
参数中提取它:
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 userInfo
dictionary, and extract it from sender
parameter in the method:
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)
这篇关于Swift:将参数传递给选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!