Using Swift 3, Xcode 8.2.1
Method:
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
describes method signature only. In your case the correct way to initialize the selector isTimer 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 touserInfo
dictionary, and extract it fromsender
parameter in the method:You cannot pass a custom parameter through a
Timer
action.Either
or
is supported, nothing else.
To pass custom parameters use the
userInfo
dictionary.