fs_tigre fs_tigre - 1 year ago 83
Swift Question

Is there a way to call a function with parameters using #selector in Swift

I have an array of

items that show when an
becomes first responder.

//... code
toolBar.items = [
UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(myFunction))]

myInputField.inputAccessoryView = toolBar

Is that possible to call
from the above example with a parameter?

Something like...

... #selector(myFunction(someParameter)))

Answer Source

Similar to UIButton, parameters can be passed via the tag attribute of UIBarButtonItem.

override func viewDidLoad() {

    let toolBar = UIToolbar()
    let firstButton = UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Done, target: self, action: #selector(myFunction))
    let secondButton = UIBarButtonItem(title: "Button 2", style: UIBarButtonItemStyle.Done, target: self, action: #selector(myFunction))
    firstButton.tag = 1
    secondButton.tag = 2
    toolBar.items = [ firstButton, secondButton ]
    textField.inputAccessoryView = toolBar

func myFunction(sender: UIBarButtonItem) {
    print("Tapped: \(sender.tag)")

Tapping a button prints the button's tag in this example:

Tapped: 1   // Tap button 1
Tapped: 2   // Tap button 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download