Welcome to OStack Knowledge Sharing 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 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...