Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Passing a parameter to selector

Tags:

ios

swift3

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?

like image 919
user1107173 Avatar asked Feb 01 '17 18:02

user1107173


People also ask

How do you pass arguments in selector method in Swift?

This is the full source code: import UIKit class ViewController: UIViewController { override func viewDidLoad() { super. viewDidLoad() let tapGesture = CustomTapGestureRecognizer(target: self, action: #selector(tapSelector(sender:))) tapGesture. ourCustomValue = "This is a value we can set" self.

Can we pass function as a parameter in Swift?

Every function in Swift has a type, consisting of the function's parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions.

How do you call a selector in Swift?

The usage of this "ValueAnimator" would be similar to a normal Timer/NSTimer, in that you pass a "selector" as an argument and that selector is called each time the ValueAnimator fires: [In Parent Class]: // { ... let valueAnimatorTest = ValueAnimator(durationInSeconds: 10, selector: #selector(self.

How do you pass parameters in OBJC func?

You cannot pass anything into a target's action method. You don't call the method; the target-action architecture calls it when the button is tapped. The action method must take one parameter, namely the sender (which in this case will be the button).


1 Answers

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

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 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)
like image 133
hybridcattt Avatar answered Sep 20 '22 11:09

hybridcattt