简体   繁体   中英

Add static parameter to #selector in Swift

Is it possible to pass an int variable via a selector, eg #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)))

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

But there is an alternative. You 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:

First approach

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

And you can receive it like this

func run(sender: UIBarButtonItem) {
    let passedInteger = sender.tag
}

But it only work if the passed parameter is a single Integer. Here's how you can do it if you want to pass multiple parameter with any data type -> Look at Second Approach

Second Approach

Subclass UIBarButtonItem

class MyBarButtonItem: UIBarButtonItem {
    var passedParameter: String?
}

And receive it like this

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

button.passedParameter = "John Doe"

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

As of https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md

#selector is just typed safe way to declare your method. So it is all about method signature, you can't add static parameter to it

For example

let sel = #selector(UIView.insertSubview(_:atIndex:)) // produces the Selector "insertSubview:atIndex:"

No, but as Edward mentioned, it may be possible to pass values through the button itself.

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

.....

func run(sender: UIButton){
     doSomething(sender.tag)
}

passing values through tags is not recommended but this is a way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM