xoogler xoogler - 5 months ago 70
iOS Question

Add static parameter to #selector in Swift

Is it possible to pass an int variable via a selector, e.g. #selector(run(1)) or #selector(run(2))

More context if necessary:

let button = UIBarButtonItem(title: "Run",
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(run(1)))

Answer

After confirmation to some iOS Developers, no you can't do this yet.

But there is an alternative. Tou can receive the sender object in the action method. You can add any property to the sender class. And receive that in action method.

for example:

Subclass UIBarButtonItem

class MyBarButtonItem: UIBarButtonItem {
    var passedParameter: String?
}

let button = MyBarButtonItem(title: "Run",
                                   style: UIBarButtonItemStyle.Plain,
                                   target: self,
                                   action: #selector(run(sender:)))

func run(sender: MyBarButtonItem) {
    // now you have the parameter
    let parameter = sender.passedParameter
}