fs_tigre fs_tigre - 3 months ago 13
Swift Question

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

I have an array of

UIToolbar
items that show when an
inputField
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
myFunction
from the above example with a parameter?

Something like...

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

Answer

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

override func viewDidLoad() {
    super.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 ]
    toolBar.sizeToFit()
    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