Add static parameter to #selector in Swift

时光毁灭记忆、已成空白 提交于 2019-12-29 09:04:08

问题


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)))

回答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
}



回答2:


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:"



回答3:


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



来源:https://stackoverflow.com/questions/37884522/add-static-parameter-to-selector-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!