Swift Selector with default argument

帅比萌擦擦* 提交于 2020-03-23 07:19:13

问题


I have Write simple Code here

self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: Selector("cancelClick"))

Actual Function

func cancelClick(isAlert:String = "yes"){
    self.dismissViewControllerAnimated(true, completion: { () -> Void in

        if isAlert == "yes" {
            Functions.displayAlert("called")
        }
    })
 }
  1. self.cancelClick() - Worked but if i didn't pass the argument
  2. self.cancelClick(isAlert:"no") - Crashed

So what should be my selector if i have to pass argument in default perameter tried with both Selector("cancelClick") and Selector("cancelClick:") but no luck.


回答1:


The thing is that the parameter is not up to you. It is always the button (the "sender"), and that is the only thing it can be.

In other words, if you want this function to have a parameter, then by all means you will need to set your selector string as "cancelClick:" - the colon means that it takes a parameter. But that parameter must be the button:

func cancelClick(bbi:UIBarButtonItem?) {

However, you will notice that I have cleverly made this UIBarButtonItem parameter an Optional. Why do you think I did that? Because now you can also call it directly and pass nil:

self.cancelClick(nil)

Thus, cancelClick: now has a way to know whether the call comes from the tapping of a button or by a direct call - if bbi is not nil, the button was tapped; if bbi is nil, we were called directly from code. Sneaky, eh?

Another sneaky approach is to make the parameter an AnyObject:

func cancelClick(sender:AnyObject) {

The beauty of this is that you can call it with any kind of class instance. cancelClick can check the type of the sender. If it is a UIBarButtonItem (sender is UIBarButtonItem), then we were called by tapping the button. Otherwise, if called in code, you can pass in a string or anything else that this function might be prepared to deal with.




回答2:


Don't use Selector("cancelClick:"), try instead just "cancelClick:" with the colon so you can pass an argument.

And as Matt said, the argument you must pass is the sender (the button) itself.



来源:https://stackoverflow.com/questions/30697003/swift-selector-with-default-argument

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