Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios - 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)))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...